Home > Mobile >  Typescript: Pick keys from function argument
Typescript: Pick keys from function argument

Time:12-16

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'.

CodePudding user response:

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

TypeScript playground

  • Related