簡體   English   中英

Typescript:從 function 參數中選擇密鑰

[英]Typescript: Pick keys from function argument

我有一個 function 第一個參數確定結果的鍵。 只給結果中的一個鍵,我可以創建一個 function,如下所示:

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))

現在我想修改這個 function,所以它可以獲取一個屬性列表並返回一個只包含給定鍵的 object。 用類似的東西修改我的代碼

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

不起作用,因為該數組與“keyof MyType”不兼容。

你非常接近,只需返回Promise<Pick<MyType, T[number]>>而不是Promise<Pick<MyType, T>>

TypeScript操場

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM