Search code examples
javascripttypescriptprototypeecmascript-5

Typescript odd behaviour extending Number


I am extending Number object, so there will be a function toKM() which convert the distance (given in meters) to Kilometers.

When I use the following syntax (which IMO is the default for TypeScript), function is not working.

interface Number {
  toKM(): number
}

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

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

When I use the "traditional" form:

interface Number {
  toKM(): number
}

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

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

Is there a special case that the new syntax is not working?


Solution

  • If you use an arrow function Typescript will capture this from the declaration context, your code is compiled to this if you target below es6:

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

    Arrow functions would not have worked event if you were to use pure JS (es2015 or above) because their behavior would be equivalent to the JS above.

    You need to use a regular function and specify the type of this

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