TypeScript 根据值的类型缩小可索引类型的键
鉴于我们有一个通用的可索引类型,我如何只获取其值的类型,以便能够缩小到只有某些键?
// imagine check is a function and its second argument only allows the property `a` as it's string and raise an error if 'b' is passed
const test2 = check({ a: 'string', b: 22 }, 'b'); // error only 'a' is allowed
const test2 = check({ a: 'str', b: 'str2' }, 'b'); // ok returns 'str2'
答案#1
当然,你可以通过使用条件类型和映射类型来提取对象类型 T 中其值匹配值类型 V 的键:
type KeysMatching<T, V> = { [K in keyof T]: T[K] extends V ? K : never }[keyof T];
declare function check<T>(obj: T, k: KeysMatching<T, string>): string;
const test1 = check({ a: 'string', b: 22 }, 'b'); // error
const test2 = check({ a: 'str', b: 'str2' }, 'b'); // ok
希望这有帮助。祝你好运!
