Sergei Basharov Sergei Basharov - 1 month ago 9
TypeScript Question

How to get a name of constructor from an instance in TypeScript?

I have a basic class:

export default class UserHomeHandler {
public init() {
console.log(this.constructor.name);
}
}


Compiler complains with this error:

error TS2339: Property 'name' does not exist on type 'Function'.


How do I get 'UserHomeHandler' as string from an instance of this class?

Answer

You could create an external .d.ts file and augment the Function type in it (idea extracted from danquirk's answer on this github issue: https://github.com/Microsoft/TypeScript/issues/2076):

function-name.d.ts

interface Function {
  name: string
}

Then import that definition:

/// <reference path='function-name.d.ts'/>

export default class UserHomeHandler {
  public init() {
    // should compile
    console.log(this.constructor.name);
  } 
}

Far from elegant, I know. If you don't like this approach, you can always cast to any.

Comments