Typescript: Extending wrapper objects (e.g. Number, String, etc.)

Created on 8 Oct 2018  Â·  3Comments  Â·  Source: microsoft/TypeScript

I created an inheritance class,such as:

class NumberTest extends Number{
        constructor(numeric:number){
           super(numeric);
        }
}

Then I want to call the valueof method from an instance of NumberTest ,such as:

    const  numberTest=new NumberTest(4);
    numberTest.valueOf();

But unlucky,throw an error,as follow:

  TypeError: Number.prototype.valueOf requires that 'this' be a Number
        at NumberTest.valueOf (<anonymous>)

in the javascript,I created the same code,like this:

class NumberTest extends Number{
        constructor(numeric){
           super(numeric);
        }
}

It works well.
I think Number.prototype.valueOf method using the typeof judge it。so object type not number type。also this,I think this is a bug。 Shape up should extends base function。

Design Limitation

Most helpful comment

This simply can't work in pre ES2015 targets because ES5 and below don't have Reflect.construct, so we use Function#call; however, Number doesn't return a wrapper object when being called, so that's the cause of the discrepancy.

All 3 comments

~https://github.com/Microsoft/TypeScript/wiki/FAQ#why-doesnt-extending-built-ins-like-error-array-and-map-work~

Actually, this is not related to that issue.

Thank you.
All the problems in "#27603" and "#27602" were caused by the property "compileroptions.target" of "tsconfig.json"
The property "compileroption.target" I set in "tsconfig.json" is too low.
This minimum version should be set to "es6".
Now, I think the advantage of typescript is just the "access authority" and the "strongly typed".
Compatibility is still a bad news.

This simply can't work in pre ES2015 targets because ES5 and below don't have Reflect.construct, so we use Function#call; however, Number doesn't return a wrapper object when being called, so that's the cause of the discrepancy.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

rbuckton picture rbuckton  Â·  139Comments

Gaelan picture Gaelan  Â·  231Comments

quantuminformation picture quantuminformation  Â·  273Comments

chanon picture chanon  Â·  138Comments

sandersn picture sandersn  Â·  265Comments