[英]in Typescript, can Object.prototype function return Sub type instance?
I want to write code like 我想写类似的代码
class Place {
next: Place;
get to() : Place {
return this;
}
}
let places : Place[]= [];
..
places[0].to.next = new Place();
There are many similar classes, so I want define 'to' property to Object.prototype. 有许多类似的类,因此我想为Object.prototype定义'to'属性。
Object.defineProperty(Object.prototye,"to",{
get: function() {
return this;
}
});
But compilation has failed because of Property 'next' does not exist on type 'Object'
但是编译失败,因为Property 'next' does not exist on type 'Object'
Can I return subtype in Typescript with Object.prototype function or property? 我可以使用Object.prototype函数或属性返回Typescript中的子类型吗?
Typescript can't model exactly the beahavior you want. Typescript无法准确地建模您想要的行为。
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: 对于方法,我们可以定义一个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();
The simplest solution would be to actually use a base class for all such objects with the property typed as polymorphic this
: 最简单的解决方案是对所有此类对象使用基类,并将其属性键入为polymorphic this
:
class Base {
get to(): this { return this; }
}
class Place extends Base{
next: Place;
}
let places: Place[] = [];
places[0].to.next = new Place();
Note: Polluting the global Object
does not seem like a great idea but ultimately that is your call. 注意:污染全局Object
似乎不是一个好主意,但最终这是您的要求。
I found some solution. 我找到了解决方法。
TS have a return type "this"; TS的返回类型为“ this”;
class Entity {
self() : this {
return this;
}
}
class Place extends Entity {
where(toGo:string) {
....
}
}
and I can use place like 我可以使用像
new Place().self().where("Canada");
method self
is decleared at super class but it can return sub class type. 方法self
在超类中被清除,但它可以返回子类类型。
So, I can use place instance without type casting. 因此,我可以使用场所实例而无需类型转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.