Example 1
In this example,
- We have a Person class with a constructor that takes a name and an age.
- We use InstanceType<typeof Person> to extract the instance type of the Person class, which is equivalent to { name: string; age: number; }.
- We create an instance of Person using new Person(“Alice”, 30) and assign it to the person variable.
- TypeScript infers that person is of type PersonInstance, which allows us to access the name and age properties of the person object with type safety.
Javascript
class Person { constructor(public name: string, public age: number) { } } type PersonInstance = InstanceType< typeof Person>; const person: PersonInstance = new Person( "Alice" , 30); console.log(person.name); // "Alice" console.log(person.age); // 30 |
TypeScript InstanceType Utility Type
In this article, we are going to learn about InstanceType<Type> Utility Type in Typescript. TypeScript is a popular programming language used for building scalable and robust applications. In TypeScript, the InstanceType<Type> utility type is used to extract the instance type of a constructor function or class type. It allows you to infer the type of instances that can be created from a constructor or class.