class A {
get projections(): { [id: string]: this } { ... }
}
class B extends A {}
new B().projections // should be { [id: string]: B }
但是,键入脚本不允许在此位置使用this
类型。有什么方法可以表达我想要的吗?或者任何它不起作用的原因?Typescript:输入对象类型
class A {
get projections(): { [id: string]: this } { ... }
}
class B extends A {}
new B().projections // should be { [id: string]: B }
但是,键入脚本不允许在此位置使用this
类型。有什么方法可以表达我想要的吗?或者任何它不起作用的原因?Typescript:输入对象类型
this
不能以这种方式使用。让我建议一个代码来实现你想要的。
class A {
get projections() {
// ...
let result = {}; // <-- your return object
return (<T>(obj: T): { [id: string]: T } => result)(this);
}
}
class B extends A {}
new B().projections // => { [id: string]: B }
我不想使用匿名函数,但这是我发现得到您的结果的方式。
您可以在A
创建一个私有的帮助功能,使代码更易读:
class A {
private applyResult<T>(obj: T, result: { [id: string]: T }) {
return result;
}
get projections() {
// ...
let result = {}; // <-- your return object
return this.applyResult(this, result);
}
}
class B extends A {}
new B().projections // => { [id: string]: B }
我希望这有助于以某种方式。
'this'是指对象的特定实例,而不是类本身。这就是为什么它不起作用。 –