Home > Enterprise >  How to make single property of an object function parameter generic?
How to make single property of an object function parameter generic?

Time:12-18

I have a generic function

function test<T>(a: string, b: T, c: number)

But I would like the parameters to be a single object like so

function test(params: {a: string; b: T, c: number})

I know I can make an object generic like this

type MyObject<T> = {a: string; b: T, c: number}

But when I go to use that type as the parameter I don't know how to handle T

function test(params: MyObject<T>) // Where do I define T?

My thinking is to somehow "destructure" the params type so that typescript knows which parameter to be generic, but I couldn't get it to work

function test<{_, T, __}>(params: MyObject<T>) // Does not work as intended

Thanks.

CodePudding user response:

You're almost there, you just need to combine the generic syntax in the function definition (<T>) with the parameter list. Only the one b property changes, so {a: string; b: T, c: number} is sufficient - string and number for the other properties is fine.

function test<T>(params: {a: string; b: T, c: number}) {
    
}
  • Related