Home > Blockchain >  How to type key in object or pass them correctly in TypeScript
How to type key in object or pass them correctly in TypeScript

Time:09-14

I want to write a function that takes an array of objects and a key from the object and returns an array of objects with a key of 2 parameters and a value from the object. For some reason, when specifying the TS object, it perceives the key as a string and not the key from the object

  const getArrayByKey = <T, V extends keyof T>(array: T[], key: V): { [key in V]: T[V] }[] => {
       return array.map((item) => ({ [key]: item[key] }))
    }

Image of error

If i pass in function array with objects like { id : 1, title : '123'} and 2 parameter 'id', i want to get array with objects like { id : 1} only with id(2 parameter of function), type in returned array works correctly but i get error when return in map function { [key] : item[key] } because key is perceived as a string but not id.

Upd: I fix this error just add explicit indication to object in map function

return array.map((item) => ({ [key]: item[key] } as { [key in V] : T[V]}))

Maybe there is another way to implicitly indicate?

CodePudding user response:

How about this?

const getArrayByKey = <T, V extends keyof T>(array: T[], key: V): Pick<T, V>[] => {
    return array.map((item) => ({ [key]: item[key] }) as Pick<T, V>)
};

See it working here

  • Related