Type of Class in typescript?

I am trying to type a method, where I pass a class and a factory as an argument. Both should strongly point to type T, but the compiler is okay with the following simplified test. Is there a stronger approach to type a class reference?

type Class<T> = new (...args: any[]) => T
class A { }
class B { }
const test = <T>(type: Class<T>, factory: () => T) => { }
test(A, () => new B()) // why is this accepted?

I tried all answers from Is there a type for "Class" in Typescript? And does "any" include it?

>Solution :

TypeScript is structurally typed, commonly called duck typing.

Notice that if I make the classes themselves structurally different, you get the expected behavior:

class A { foo = "" }
class B { bar = 0 }

Playground

Leave a Reply