Refer to a class definition instead of one of its instances in TypeScript

In TypeScript, when using a class as a type, it types as an instance of this class.

ts
class Animal {}
 
let dog: Animal // `dog` is typed as an instance of the `Animal` class

To be able to type as the class definition itself, and not one of its instances, we need to use the keyof operator.

ts
class Animal {}
 
let classDefinition: typeof Animal

Declaring a class in TypeScript creates two things: a constructor (the class definition, aka. typeof Animal) and an interface for instances of the class (the type Animal).

I found the solution to my problem on 2ality article about classes as values in TypeScript.

Join my mailing list

Get monthly insights, personal stories, and in-depth information about what I find helpful in web development as a freelancer.

Email advice once a month + Free XState report + Free course on XState

Want to see what it looks like? View the previous issues.

I value your privacy and will never share your email address.