Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading