Categories
TypeScript Answers

How to add types to class constructor in TypeScript?

Spread the love

Sometimes, we want to add types to class constructor in TypeScript.

In this article, we’ll look at how to add types to class constructor in TypeScript.

How to add types to class constructor in TypeScript?

To add types to class constructor in TypeScript, we can use the typeof operator to get the type from the class.

For instance, we write

class Zoo {
  constructor(public AnimalClass: typeof Animal) {
    const a = new AnimalClass();
  }
}

to use typeof Animal to return the type for the Animal class automatically.

Then we can assume that AnimalClass is the Animal class and instantiate it in the constructor.

Conclusion

To add types to class constructor in TypeScript, we can use the typeof operator to get the type from the class.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *