引用打字稿对象中的键值

时间:2020-03-31 22:45:21

标签: typescript typing

    type obj = { a: 1, b: "one", c: true }
    function updateObj(key: keyof obj, value: obj[typeof key] ) {

    }

当前参数; updateObj函数中的value是obj类型的所有值的并集。但是,我希望它仅引用传递给函数的键的值。

1 个答案:

答案 0 :(得分:0)

使函数通用。使用通用参数表示您获得的键,并使用该参数访问键的值类型:

type obj = { a: 1, b: "one", c: true }

declare function updateObj<K extends keyof obj>(key: K, value: obj[K]);

updateObj("a", 1)      // No error
updateObj("a", 5)      // Error here
updateObj("a", false); // Error here

Playground Link