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

Get value from object of unknown content by key in typescript

I’m writing function that’ll return single value from object by key or return empty object if key does not exist.

Code:

//example data:
const obj = {
    data: {test: 'word'},
    str: 'Hi',
    num: 22,
}

const pickOne = <T extends object>(obj: T, key: keyof typeof obj) => ((key in obj) ? obj.key : {})

console.log(pickOne(obj, 'data')) //should print {test: 'word'}

My problem is that I get this error: Property 'key' does not exist on type 'T'.
I’m new to typescript but after reading docs I was sure that keyof typeof would allow any key in obj.

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

Any help would be appreciated, thanks.

>Solution :

This:

obj.key

gets the property named "key" on obj, which may not exist.

Where this:

obj[key]

Gets the property name in the variable key.

Which works without type error: See playground

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