fignuts fignuts - 1 year ago 181
TypeScript Question

How do I refer a value of an object as a generic in typescript?

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.

Answer Source

You can use lookup 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>(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;
}

Hope that helps; good luck!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download