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

Can you take a class as an argument and build a type from it in TypeScript?

I have a function that takes a class as an argument, and uses an interface based on that class as a type.

What the function does is not important!. Please don’t make me repost it here (it’s long and 99% of it has nothing whatsoever to do with the question I’m asking, so I’ve made a dummy question here instead).

Everything works great when I take the type as a generic type argument:

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

class SomeClass{}

interface SomeClassType extends SomeClass {}

// Use them together
doSomething<SomeClassType>(SomeClass, 1234);

// Example doSomething function
const doSomething = <T,> (
  // I found this "type for a class" in another SO post, but I'm
  // not sure it's correct, and it may be the root of my problem
  SomeClass: { new(...args: any[]): any; },
  x: any
) => {
  // Does something with x, SomeClass, and T
}

However, it felt redundant to have to pass T and SomeClass, so I figured, why not pass just the class, and derive its type inside my function? So, I tried to do that:

const doSomething = (
  SomeClass: { new(...args: any[]): any; },
  x: any
) => {
  interface T extends SomeClass {}
  // Does something with x, SomeClass, and T
}

However, that gets me an error:

‘SomeClass’ refers to a value, but is being used as a type here. Did you mean ‘typeof SomeClass’?ts(2749)

My question is simple: in TS, can you pass a class as an argument, and then create a type from it … and if so how?

>Solution :

You still need the generic. You just need to use it in the type of the class – it looks like you want T to be the type of the class instances, which is the return type of the constructor:

const doSomething = <T,> (
  SomeClass: { new(): T; },
//                    ^
  x: unknown
) => {
  // …
}

Then T can be inferred from the class object you’re passing.

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