typescript - 箭头函数和 Nest 的装饰器?
我正在尝试在控制器中使用带有 NestJS 装饰器的箭头函数。
那么有可能做类似这样的事情吗:
@Controller()
export class AppController {
@Get()
findAll = (): string => 'This is coming from a fat arrow !';
}
使用这段代码,TypeScript 告诉我:Unable to resolve signature of property decorator when called as an expression,所以它无法工作。
我更喜欢使用胖箭头函数,而不是这个“传统”函数:
@Controller()
export class AppController {
@Get()
findAll(): string {
return 'This is not comming from a fat arrow';
}
}
这就是为什么我在问这样的事情是否可能。
答案#1
我会说答案是否定的,原因正是 箭头函数 与 JavaScript 中的 函数 的不同之处,即改变了词法作用域下的 this 和 arguments。这个答案详细说明了 function() {} 与 myFunction =() => {} 的区别。
除此之外,使用箭头函数会禁止大量使用类函数,因此如果你注入了任何服务的实例,你将无法使用它们。
@Injectable()
export class AppController {
constructor (private readonly appService: AppService) {}
@Get('/')
hello(): string {
return this.appService.sayHello();
}
}
将起作用并返回 appService.sayHello() 函数的字符串,但这
@Injectable()
export class AppController {
constructor (private readonly appService: AppService) {}
@Get('/')
hello = (): string => {
return this.appService.sayHello();
}
}
不会返回 appService.sayHello() 函数的字符串,因为它不知道 appService。
