fignuts
fignuts

Reputation: 250

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.

Upvotes: 3

Views: 5488

Answers (1)

jcalz
jcalz

Reputation: 330456

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;
}

Upvotes: 6

Related Questions