打字稿奇怪的行为扩展数字

Typescript odd behaviour extending Number

我正在扩展 Number 对象,所以会有一个函数 toKM() 将距离(以米为单位)转换为公里。

当我使用以下语法时(IMO 是 Typescript 的默认语法),功能不起作用。

interface Number {
  toKM(): number
}

Number.prototype.toKM = () => {
  return this / 1000
}

let alfa = 3456
document.write(alfa.toKM())

当我使用 "traditional" 形式时:

interface Number {
  toKM(): number
}

Number.prototype.toKM = function() {
  return this / 1000
}

let alfa = 3456
document.write(alfa.toKM())

是否存在新语法不起作用的特殊情况?

如果你使用箭头函数,Typescript 将从声明上下文中捕获它,如果你的目标低于 es6,你的代码将编译为此:

var _this = this;
Number.prototype.toKM = function () {
    return _this / 1000;
};

如果您使用纯 JS(es2015 或更高版本),箭头函数将不会起作用,因为它们的行为等同于上述 JS。

您需要使用正则函数并指定this

的类型
Number.prototype.toKM = function(this: number) {
  return this / 1000
}