[英]TypeScript narrow down the keys of indexable type by its value types
Given we have a generic indexable type how can I retrieve only the types of its values to be able to narrow down to only some of the keys? 给定我们有一个通用的可索引类型,我该如何仅检索其值的类型以缩小到仅某些键?
// 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'
Sure, you can do this by using conditional and mapped types to extract just the keys of an object type T
whose values match a value type V
: 当然,您可以通过使用条件类型和映射类型仅提取对象类型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
Hope that helps. 希望能有所帮助。 Good luck! 祝好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.