I was trying to extract some properties from an object.
The keys which should be extracted are given as parameter to the function.
For example, for this code, it copies the specific keys from the object and returns new, another object with the same keys.
function pick(source: object, ...keys: string[]) {
const returnValue = {}
for (const key in source) {
const index = keys.indexOf(key)
if (index < 0) continue
keys.splice(index, 1)
returnValue[ key ] = source[ key ]
}
return returnValue
}
When I use this function, TypeScript infers the return type as {} which is an empty object. Is there a way I can get this as { [key: .. in parameter 'keys' ..]: any }?
I tried this but it did not work.
function pick<O>(source: object, ...keys: (keyof O)[]): O {
const returnValue: O = {}
for (const key in source) {
const index = keys.indexOf(key)
if (index < 0) continue
keys.splice(index, 1)
returnValue[ key ] = source[ key ]
}
return returnValue
}
Thank You