2

In typescript how do you retrieve Class name from within the Class itself?

For example, given the following code:

export class SomeRandomName extends AbstractSomething<SomeType> implements OnDestroy {

  className = 'SomeRandomName';

is there a way to automatically assign to className variable the name of the class SomeRandomName?

Thanks in advance.

2
  • instanceOfSomeRandomName.constructor.name Commented Jun 1, 2021 at 14:33
  • @enno.void thank you; however, one needs to instantiate a class object first and then assign the class name through instanceOfSomeRandomName.constructor.name. Can I assign it from within the Class itself? Commented Jun 1, 2021 at 14:59

2 Answers 2

3

You can simply do this:

export class SomeRandomName extends AbstractSomething<SomeType> implements OnDestroy {
      getName() {
        return (this as any).constructor.name;
      }
}
Sign up to request clarification or add additional context in comments.

Comments

2

A TypeScript class is just an ES6 class. You can get the name of the class as a string from .constructor.name

class Foo {}

const foo = new Foo();
console.log(foo.constructor.name); // Foo

2 Comments

Thank you; is there a way to assign the class name from within the class itself and not through a class instance, e.g. without creating a class object?
I expect Andrew means: from within the Constructor itself; For the record I have not found a way to access the class prototype from within its own Constructor. But would be pleased if someone finds a way. (I often to this to name instances from within the constructor, and so far it seems to require making a string copy of the class name; seems ugly & not DRY)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.