TypeScript 通过其值类型缩小可索引类型的键

Posted

技术标签:

【中文标题】TypeScript 通过其值类型缩小可索引类型的键【英文标题】:TypeScript narrow down the keys of indexable type by its value types 【发布时间】:2019-08-10 15:05:31 【问题描述】:

鉴于我们有一个通用的可索引类型,我怎样才能只检索其值的类型以便能够缩小到只有一些键?

// 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】:

当然,您可以通过使用conditional 和mapped 类型来仅提取对象类型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 

希望对您有所帮助。祝你好运!

【讨论】:

以上是关于TypeScript 通过其值类型缩小可索引类型的键的主要内容,如果未能解决你的问题,请参考以下文章