5

Closed

Use type of 'valueOf' member to determine operator result types

description

The following demonstrates a small example of a library defining an object that allows using + correctly on variables of this type:
function MyNumber(primitiveNumber) {
    this.wrapped = primitiveNumber;
}

MyNumber.prototype.valueOf = function () {
    return this.wrapped;
};

var x = new MyNumber(3),
    y = new MyNumber(5),
    z = x + y;
console.log(z); // 8
However, Typescript currently does not allow this:
interface MyNumber {
    (wrapped: number): MyNumber;
    
    valueOf(): number;
}

var x: MyNumber,
    y: MyNumber,
    z = x + y; // Invalid "+" expression – types not known to support the addition parameter
Is it possible to allow Typescript to recognize that valueOf has been overridden to return number and infer the correct type (and more importanty, allow an addition)?
Closed Jul 28, 2014 at 10:18 PM by jonturner
As part of our move to GitHub, we're closing our CodePlex suggestions and asking that people move them to the GitHub issue tracker for further discussion. Some feature requests may already be active on GitHub, so please make sure to look for an existing issue before filing a new one.

You can find our GitHub issue tracker here:
https://github.com/microsoft/typeScript/issues

comments

jamesnw wrote Apr 21, 2014 at 2:13 AM

I brought this up also in a comment a couple weeks ago:
https://typescript.codeplex.com/workitem/2408

...but forgot to put in the request - but very interested to see how this progresses. ;)

RyanCavanaugh wrote Apr 21, 2014 at 4:59 PM

Definitely doable, though lower priority. Changing title to clarify the requested behavior.