0

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

2
  • Is the array known at compile-time (is static)? What is the foo property in the array for? How are you using the function? Commented Oct 24, 2022 at 20:48
  • The array is known at compile time. I'm trying to make a react component reusable, which takes in a list of items to be rendered, and also takes an onSubmit callback. I want the data thats passed into the callback to be known. I realize that the example I used could be misleading. I meant string not foo Commented Oct 25, 2022 at 12:13

1 Answer 1

1

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'}]);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I was able to take the concepts you showed and apply them to my problem and sure enough, it worked. I'll stop beating my head in to a wall for now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.