问题描述
例如假设我们有
type AnObject = {
a: string
b: number
c: string
d: number
}
type ExtractKeysOfType<O extends {[K: string]: any}, T> = ///...
type StringKeys = ExtractKeysOfType<AnObject, string> // 'a' | 'c'
它们是实现 ExtractKeysOfType
的方法吗?
Is they're a way to achieve ExtractKeysOfType
?
推荐答案
您可以在此处结合使用映射类型和条件类型:
You can use mapped types combined with conditional types here:
type ExtractKeysOfType<T, Target> = {
[K in keyof T]: T[K] extends Target ? K : never
}[keyof T];
这基本上是通过遍历 T 类型中的每个键来工作的.T[K]
是否扩展了我们的 Target 类型?如果是这样,那就太好了,并且属性值就是那个 Key.如果不是,则该键的类型为 never
.
This essentially works by going over each key in type T. Does T[K]
extend our Target type? if so, great, and the property value is simply that Key. If not, that key has type never
.
对于您的情况,这种中介类型如下所示:
This intermediary type, for your case, looks like:
{
a: "a";
b: never;
c: "c";
d: never;
}
然后,该中间类型被 T 的键再次索引.这将产生您想要的联合,因为 never
类型在这里被编译器忽略.
Then, that intermediary type is indexed again by keys of T. This will produce your desired union, since the never
types are ignored by the compiler here.
这篇关于从集合中仅收集特定类型值的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!