[英]How to extract keys of certain type from object
Lets say I have an interface Obj
:假设我有一个接口
Obj
:
interface Obj {
string1: string
string2: string
array1: SomeInterface[]
array2: SomeOtherInterface[]
}
How can one extract the keys of the interface Obj
that extends []
as a discriminated union type?如何将扩展
[]
的接口Obj
的键提取为可区分的联合类型?
Desired output given Obj
from above:从上面给定的
Obj
所需的输出:
// "array1" | "array2"
You need to use mapped types :您需要使用映射类型:
type SomeInterface = { tag: 'SomeInterface' }
type SomeOtherInterface = { tag: 'SomeOtherInterface' }
interface Obj {
string1: string
string2: string
array1: SomeInterface[]
array2: SomeOtherInterface[]
}
type ObtainKeys<Obj, Type> = {
[Prop in keyof Obj]: Obj[Prop] extends Type ? Prop : never
}[keyof Obj]
type GetArrayKeys = ObtainKeys<Obj, Array<any>> // "array1" | "array2"
type GetStringKeys = ObtainKeys<Obj, string> // "string1" | "string2"
ObtainKeys
is a generic util, which expects two arguments. ObtainKeys
是一个通用的工具,它需要两个参数。 First one is an Object you want to check, second one is a type you want to extract.第一个是您要检查的对象,第二个是您要提取的类型。
This line: [Prop in keyof Obj]: Obj[Prop] extends Type ? Prop : never
这一行:
[Prop in keyof Obj]: Obj[Prop] extends Type ? Prop : never
[Prop in keyof Obj]: Obj[Prop] extends Type ? Prop : never
iterates over all Obj
keys and checks whether Obj[Prop]
extends desired type. [Prop in keyof Obj]: Obj[Prop] extends Type ? Prop : never
迭代所有Obj
键并检查Obj[Prop]
是否扩展了所需的类型。 Please keep in mind, that Obj[Prop]
is a value and not a key.请记住,
Obj[Prop]
是一个值而不是一个键。 So, if Obj[Prop]
meets the requirements - return Prop
, otherwise - never
.因此,如果
Obj[Prop]
满足要求 - 返回Prop
,否则 - never
。
I have used [keyof Obj]
in order to get all values of our iterated type, because desired Prop
is in the value
place and union of any type with never
- returns you same type without never
我已经使用
[keyof Obj]
来获取我们迭代类型的所有值,因为所需的Prop
位于任何类型的value
位置和联合中,并且never
- 返回相同类型而没有never
I would like to add that this syntax is also possible for the same use case:我想补充一点,这种语法也适用于相同的用例:
type ObtainKeys<T, V> = keyof {
[K in keyof T as T[K] extends V ? K : never]: any
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.