简体   繁体   English

强制“keyof object”,排除值不是特定类型的键

[英]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.

相关问题 如何强制 object 的某些嵌套键属于特定类型? - How to enforce that some nested keys of an object are of a certain type? 在 TypeScript 中,如何获取值属于给定类型的 object 类型的键? - In TypeScript, how to get the keys of an object type whose values are of a given type? 如何表达其值都具有特定类型的对象类型 - How to express an object type whose values all have a certain type TypeScript 类型为 object 其值与其键匹配 - TypeScript type for object whose values match its keys Typescript:如何键入 object,其值取决于键 - Typescript: How to type an object whose values depend on the keys Typescript 某类密钥 - Typescript keyof of a certain type 打字稿:定义对象类型而不定义键的类型以获取 keyof - Typescript: Define object type without defining types for keys to get keyof 为什么 Object.keys 在 TypeScript 中不返回 keyof 类型? - Why doesn't Object.keys return a keyof type in TypeScript? 是否可以在不为其键显式设置类型的情况下强制执行对象值的类型? - Is it possible to enforce the type of an object's values without explicitly setting a type for its keys? 强制 object 包含枚举的所有键,并且仍然对其值进行类型推断 - Enforce object to contain all keys of an enum and still have type inference for it's values
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM