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

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

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

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

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.

>Solution :

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}) {
    
}
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