Home:ALL Converter>Type Detection in TypeScript

Type Detection in TypeScript

Ask Time:2016-01-17T18:39:27         Author:Kaveh Shahbazian

Json Formatter

Is there a way to get the name of a type of a caller of a function in TypeScript? Alternatively is there a way to get the name of the type of the current object?

Something like:

export class SomeData {
    sampleFunc() {
        console.log(this.getTypeName());
    }

    //or
    anotherFunc(caller: any) {
        console.log(caller.getTypeName());
    }
}

getTypeName is the desired functionality here. The types in TypeScript vanish after compiling. There is typeof (to get the class definition object itself) but I can not see how to get the name.

One usage for this could be cleaner logging with console.group(name) and console.groupEnd() - at least at development time.

Edit:

As far as I've searched, there is a Polyfill for Metadata Reflection API proposal "to add Decorators to ES7, along with a prototype for an ES7 Reflection API for Decorator Metadata". One can use that cooperatively along with decorators in TypeScript.

Author:Kaveh Shahbazian,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/34837377/type-detection-in-typescript
yy