1

I have a function which first argument determines the keys of the result. Given only one key in the result, I can create a function like the following:

type MyType = {
    green: string;
    red: string;
    blue: string;
}

async function fetchStuff<T extends keyof MyType>(properties: T): Promise<Pick<MyType, T>> {
    const result = await fetch("http://localhost", {
        method: "POST",
        body: JSON.stringify({
            "properties": properties
        })
    });
    
    return await result.json();
}

// Works fine
console.log(fetchStuff("green").then(x => x.green))

// Syntax error - as expected
console.log(fetchStuff("green").then(x => x.red))

Now I want to modify this function, so it can take a list of properties and return a object containing only the given keys. Modifying my code with something like

async function fetchStuff<T extends Array<keyof MyType>>(properties: T): Promise<Pick<MyType, T>>

did not work, as the array is not compatible with 'keyof MyType'.

1 Answer 1

2

You were pretty close, just return Promise<Pick<MyType, T[number]>> instead of Promise<Pick<MyType, T>>

TypeScript playground

Sign up to request clarification or add additional context in comments.

1 Comment

Would you care to elaborate what adding [number] does, and why it works?

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.