在Typescript中,Object.prototype函数可以返回Sub类型实例吗? [英] 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'属性.
There are many similar classes, so I want define 'to' property to Object.prototype.
Object.defineProperty(Object.prototye,"to",{
get: function() {
return this;
}
});
但是由于类型'对象'不存在属性'next'
我可以使用Object.prototype函数或属性返回Typescript中的子类型吗?
Can I return subtype in Typescript with Object.prototype function or property?
推荐答案
Typescript不能精确建模所需的行为.
Typescript can't model exactly the beahavior you want.
我能想到的最接近的方法是使用方法而不是属性.对于方法,我们可以定义一个 this
参数并推断其类型并将其用作返回类型:
The closest I can think of is to use a method not a property. For methods we can define a this
parameter and infer it's type and use it as the return type:
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
的所有此类对象实际使用基类:
The simplest solution would be to actually use a base class for all such objects with the property typed as 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
似乎不是一个好主意,但最终这是您的要求.
Note: Polluting the global Object
does not seem like a great idea but ultimately that is your call.
这篇关于在Typescript中,Object.prototype函数可以返回Sub类型实例吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!