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

Where in Typescript Generics

I have a function that takes an object and a name of a class (which is contained by that object). Getting all the properties of an object isn’t hard (keyof O), and figuring out if a key is a class isn’t hard either (O[N] extends {new: (..args: any[]) => any}). However, I cant combine them:

function foo<O, N extends keyof O where O[N] extends {new: (...args: any[]) => any}> (obj: O, name: N){}

I have seen Extract<T, U>, but I can not use T inside of the check for U. How else would I go about this?

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 :

There is no such syntax, you can add a constraint to O instead to force the N key to have whatever type you need it to have:

function foo<O extends Record<N, new (...a: any) => any>, N extends keyof O> (obj: O, name: N){

}

let o = {
    a: class {},
    b: class {},
    c: 0,
}

foo(o, "a") // ok
foo(o, "c") // error

Playground Link

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