Home > OS >  Get Class Name of Class Subclassing Array in TypeScript?
Get Class Name of Class Subclassing Array in TypeScript?

Time:10-06

I have the following class (ported from JavaScript wherein this works [prior to adding the types]) within TypeScript:

class A extends Array {
    private _foo: string;

    constructor(settings: any) {
        super();
        this._foo = 'foo';
    }

    get Foo() {
        return (this._foo);
    }
    set Foo(value) {
        this._foo = value;
    }
}
let test = new A({ });
test.push('1');
test.push(2);
test.push('3');

// outputs "A" in JavaScript
// outputs "Array" in TypeScript
console.log(test.constructor.name);

The issue is outlined at the bottom of the code snippet, I'm expecting to get the class name back from test.constructor.name of "A" but am instead getting "Array". It seems like in the specific case of subclassing Array objects, TypeScript blows away the constructor name. Is there a way to find the class name within TypeScript which doesn't rely upon .constructor.name?

CodePudding user response:

I've tested your code in the enter image description here

CodePudding user response:

This happens because you have es5 as a target in compilerOptions and Typescript polyfills class

Have a look at generated code for es5 vs ES2015.

If you don't need to support really old browsers you can safely use a higher target than es5

  • Related