【发布时间】:2022-01-18 19:55:15
【问题描述】:
我有一个函数,它的第一个参数决定了结果的键。如果结果中只有一个键,我可以创建如下函数:
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”不兼容。
【问题讨论】:
标签: typescript types