我有一個函式,它的第一個引數決定了結果的鍵。給定結果中只有一個鍵,我可以創建一個如下所示的函式:
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))
現在我想修改這個函式,所以它可以接受一個屬性串列并回傳一個只包含給定鍵的物件。用類似的東西修改我的代碼
async function fetchStuff<T extends Array<keyof MyType>>(properties: T): Promise<Pick<MyType, T>>
不起作用,因為該陣列與“keyof MyType”不兼容。
uj5u.com熱心網友回復:
你很接近,只是回傳Promise<Pick<MyType, T[number]>>而不是Promise<Pick<MyType, T>>
打字稿游樂場
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/382661.html
下一篇:Angular:關于表單更改事件
