Markos Sankey
Markos Sankey

Reputation: 3

Typescript: Build Object Type from Array of Objects' Property Values

I'm trying to build a generic type (Response) that will be an object containing all values from KeysForResponse, which is the values from the valueIWant property for each object in MyObject[]. I can't seem to figure it out, or if its even possible. Basically, if I pass the following array into a function:

[{valueIWant: 'makeMeAKey', foo: 'bar'}, {valueIWant: 'alsoMakeMeAKey', foo: 'bar'}]

I want to return the following type:

{makeMeAkey: string, alsoMakeMeAKey: string}

Here is what I currently have, which isn't generic

interface MyObject {
  valueIWant: string;
  nonImportantValue: string;
}

type KeysForResponse = Array<MyObject>[number]['valueIWant'];

type Response = {
  [K in KeysForResponse]: string;
};

Upvotes: 0

Views: 392

Answers (1)

vabatch_dev
vabatch_dev

Reputation: 115

You must define a generic parameter for the value of that key

type MyObject<T> = {
    valueIWant: T;
}

function fn <T extends string, O extends MyObject<T>> (request: O[]) : {[x in O["valueIWant"]]: string}  {
    return request.reduce((acc, curr) => {
        return {
            ...acc,
            [curr.valueIWant]: 'foo'
        }
    }, {} as {[x in O["valueIWant"]]: string})
}

const result = fn([{valueIWant: 'key1', foo: 'foo'}, {valueIWant: 'key2', foo: 'foo2'}]);

Upvotes: 1

Related Questions