Home > Net >  Where in Typescript Generics
Where in Typescript Generics

Time:01-25

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?

CodePudding user response:

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

  •  Tags:  
  • Related