我想写这样的代码
class Place {
next: Place;
get to() : Place {
return this;
}
}
let places : Place[]= [];
..
places[0].to.next = new Place();
有很多类似的类,所以我想为 Object.prototype 定义“to”属性。
Object.defineProperty(Object.prototye,"to",{
get: function() {
return this;
}
});
但是编译失败,因为 Property 'next' does not exist on type 'Object'
我可以使用 Object.prototype 函数或属性在 Typescript 中返回子类型吗?
最佳答案
Typescript 无法准确模拟您想要的行为。
我能想到的最接近的是使用方法而不是属性。对于方法,我们可以定义一个 this
参数并推断它的类型并将其用作返回类型:
class Place extends Object{
next: Place;
}
let places: Place[] = [];
interface Object{
to<T>(this: T):T;
}
Object.prototype.to = function () {
return this;
};
places[0].to().next = new Place();
最简单的解决方案是为所有此类对象实际使用一个基类,其属性类型为多态 this
:
class Base {
get to(): this { return this; }
}
class Place extends Base{
next: Place;
}
let places: Place[] = [];
places[0].to.next = new Place();
注意:污染全局 Object
似乎不是一个好主意,但最终这是你的决定。
关于javascript - 在 Typescript 中,Object.prototype 函数可以返回 Sub 类型实例吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53927276/