引用打字稿对象中的键值
Reference the value of a key in a typescript object
type obj = { a: 1, b: "one", c: true }
function updateObj(key: keyof obj, value: obj[typeof key] ) {
}
当前参数; updateObj 函数中的值是 obj 类型的所有值的联合。但是,我希望它仅引用传递给函数的键的值。
使函数通用。使用通用参数来表示您获得的键,并使用它来访问键的值类型:
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
type obj = { a: 1, b: "one", c: true }
function updateObj(key: keyof obj, value: obj[typeof key] ) {
}
当前参数; updateObj 函数中的值是 obj 类型的所有值的联合。但是,我希望它仅引用传递给函数的键的值。
使函数通用。使用通用参数来表示您获得的键,并使用它来访问键的值类型:
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