TypeScriptUtility types

InstanceType<Type>

Gets the type of the object a class constructor creates.

On this page

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 InstanceType for generic code.
  • For the type of constructor parameters, use ConstructorParameters<typeof Class>.

Related entries

#

Spotted a mistake or missing an example? Write to us.