TypeScriptUtility types
InstanceType<Type>
Gets the type of the object a class constructor creates.
Example
#TypeScript
class Badge {
constructor(public name: string) {}
}
class Certificate {
constructor(public course: string) {}
}
function create<C extends new (arg: string) => object>(Cls: C, arg: string): InstanceType<C> {
return new Cls(arg) as InstanceType<C>
}
const badge = create(Badge, '7-day streak')
const cert = create(Certificate, 'HTML and CSS')
console.log(badge.name, '|', cert.course)Result
7-day streak | HTML and CSS
Definition and usage
#InstanceType<Type> takes a constructor type and returns the type of the object it creates. For typeof Player the result is the type Player.
In everyday code, a class is already the type of its own instances, so InstanceType is mainly useful in generic code: factories, class registries, and functions that take a class as an argument.
For abstract classes, you need to use the type abstract new (...args: any) => any in the type parameter’s constraint.
Syntax
#Syntax
type Instance = InstanceType<typeof Class>Type parameters
#Type
constructor type
The type of a class or a constructor function.
Good practices
#- In typical code, the class name alone works fine as a type. Save
InstanceTypefor generic code. - For the type of constructor parameters, use
ConstructorParameters<typeof Class>.
Related entries
#- ReturnType<Type>Gets the type of the value a function returns.
- Generics <T>Types and functions with a type parameter that work for many types without losing precision.
- abstract classA base class you can’t create directly, with methods for its descendants to fill in.
- ConstructorParameters<Type>Gets the types of a class constructor’s parameters as a tuple.
Spotted a mistake or missing an example? Write to us.