Issue
I'm trying to write a signature for this function:
export function objToArray(obj){
let ret = [];
for(const key of Object.keys(obj)){
ret.push(Object.assign({objKey: key.toString()}, obj[key]));
}
return ret;
}
So for an object of type T that contains values of type U I want to return Array<U & {objKey: string}>
. I can't figure out how to do this with typescript.
Solution
You can use indexed access types. A type T
has keys of type keyof T
and values of type T[keyof T]
. Your function would therefore be typed like this:
export function objToArray<T extends object>(
obj: T): Array<T[keyof T] & { objKey: string }>{
let ret = [];
// Object.keys() returns `string[]` but we will assert as `Array<keyof T>`
for(const key of Object.keys(obj) as Array<keyof T>){
ret.push(Object.assign({objKey: key.toString()}, obj[key]));
}
return ret;
}
Answered By - jcalz
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.