javascript - 在 Typescript 中,Object.prototype 函数可以返回 Sub 类型实例吗?

标签 javascript typescript get subtype defineproperty

我想写这样的代码

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/

相关文章:

javascript - 在网站的新页面上保持 jquery 下拉菜单打开

javascript - 单击书签时意外打开新页面

angular - 我应该如何在 Angular 中使用 ES2020?

reactjs - 如何在 ReactJs 中使用 Typescript 为状态赋值并使用 setState

javascript - 隐藏 URL 中传递的变量

node.js - Nodejs http 请求不工作

javascript - JS字符串变量: why aren´t special characters substituted?

javascript - 在 Nginx 代理后面刷新页面后,我的 Angular 6 路由返回 404

Java单向链接整数列表,编写函数返回对列表中索引为I的元素的引用

php - 如何根据下拉选择更改范围的内容