【问题标题】:Typescript: Pick keys from function argument打字稿:从函数参数中选择键
【发布时间】: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


    【解决方案1】:

    您已经很接近了,只需返回 Promise&lt;Pick&lt;MyType, T[number]&gt;&gt; 而不是 Promise&lt;Pick&lt;MyType, T&gt;&gt;

    TypeScript playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-29
      • 1970-01-01
      • 2021-05-16
      • 2020-05-22
      相关资源
      最近更新 更多