chrispytoes
chrispytoes

Reputation: 1889

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

In other words, is there some way to enforce keyof (Foo[keyof Foo] extends object[]), or something to that degree?

Upvotes: 0

Views: 249

Answers (1)

Aron
Aron

Reputation: 9248

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] pattern see this answer.

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.

Upvotes: 2

Related Questions