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.

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

Leave a Reply