[英]Enforce “keyof object”, excluding keys whose values are not a certain type
So, I know how to use keyof ObjectType
to enforce any keys of an object.所以,我知道如何使用
keyof ObjectType
来强制执行对象的任何键。 What I want now is to do the same thing, but only include keys whose values match a certain type.我现在想要的是做同样的事情,但只包括其值匹配某种类型的键。
So if I had:所以如果我有:
interface Foo {
myProp: string
someProp: number
anotherProp: object[]
}
I want to get the keyof Foo
type, but only include keys whose values extend object[]
.我想获得
keyof Foo
类型,但只包含其值扩展object[]
键。
In other words, is there some way to enforce keyof (Foo[keyof Foo] extends object[])
, or something to that degree?换句话说,是否有某种方法可以强制执行
keyof (Foo[keyof Foo] extends object[])
或某种程度的强制执行?
We can do this with a helper that makes use of conditional and index types .我们可以使用一个使用条件和索引类型的助手来做到这一点。
type ObjectArrayKeys<T> = { [K in keyof T]: T[K] extends object[] ? K : never }[keyof T]
For a step by step explanation of the { [K in keyof T]: T[K] extends ... ? K : never }[keyof T]
有关
{ [K in keyof T]: T[K] extends ... ? K : never }[keyof T]
的逐步说明{ [K in keyof T]: T[K] extends ... ? K : never }[keyof T]
{ [K in keyof T]: T[K] extends ... ? K : never }[keyof T]
pattern see this answer . { [K in keyof T]: T[K] extends ... ? K : never }[keyof T]
模式见这个答案。
Using this helper we can do:使用这个助手我们可以做到:
interface Foo {
myProp: string
someProp: number
anotherProp: object[]
}
type FooObjArrayKeys = ObjectArrayKeys<Foo>
// type FooObjArrayKeys = "anotherProp"
Now FooObjArrayKeys
equals "anotherProp"
, which is the only key in the interface that matches.现在
FooObjArrayKeys
等于"anotherProp"
,这是接口中唯一匹配的键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.