[英]in Typescript, can Object.prototype function return Sub type instance?
我想写类似的代码
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();
最简单的解决方案是对所有此类对象使用基类,并将其属性键入为polymorphic this
:
class Base {
get to(): this { return this; }
}
class Place extends Base{
next: Place;
}
let places: Place[] = [];
places[0].to.next = new Place();
注意:污染全局Object
似乎不是一个好主意,但最终这是您的要求。
我找到了解决方法。
TS的返回类型为“ this”;
class Entity {
self() : this {
return this;
}
}
class Place extends Entity {
where(toGo:string) {
....
}
}
我可以使用像
new Place().self().where("Canada");
方法self
在超类中被清除,但它可以返回子类类型。
因此,我可以使用场所实例而无需类型转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.