假设我有一个A装饰器应用于返回字符串的方法。装饰器使用该字符串并最终返回B类型(一个类)。
class B {
constructor(text: string) { ... }
method() {...}
}
class X {
@A
someMethod(): string {
return 'lalala';
}
}
Run Code Online (Sandbox Code Playgroud)
装饰者
function A(target, property, descriptor) {
const text: string = descriptor.value();
descriptor.value = () => new B(text);
}
Run Code Online (Sandbox Code Playgroud)
发生了什么?现在someMethod返回一个B对象而不是字符串。但我不能做这样的事情:
class X {
constructor() {
this.someMethod().method();
}
@A
someMethod(): string {
return 'lala';
}
}
Run Code Online (Sandbox Code Playgroud)
为什么?因为someMethod从定义中是字符串类型,但装饰器使其返回B类型。我可以以某种方式让打字稿知道someMethod实际上返回B,而不是string?