Earleking
Earleking

Reputation: 79

How to use a class type as a typed variable? (Typescript)

Lets say you have an interface then classes that implement it.

interface A { /*do stuff*/ }

class B implements A { /*do stuff*/ }

class C implements A { /*do stuff*/ }

Then if you have a variable that can store the class type, not a specific instance of an object, what do you put as the type?

let x: Something = B; // or C

I know for objects you can use typeof, but for interfaces you can't. However I am able to specify variables to store implementations of interfaces so I don't see why I shouldn't be able to store classes of an interface.

Upvotes: 0

Views: 529

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249466

You can use a constructor signature (similar to a function signature, but with a new in front of it):

interface A { /*do stuff*/ }

class B implements A { /*do stuff*/ }

class C implements A { /*do stuff*/ }


let x: new () => A = B;
let x2: new () => A = C;

Playground Link

Upvotes: 1

Related Questions