Дарья
Дарья

Reputation: 167

Typescript: define type like keyof but with specific value type

I have interface

interface MyInterface {
  field1: boolean,
  field2: MyType,
  field3: MyType
}

and I want to create type that contains keys of this interface but only those which usage in interface gives value with type MyType. I know about existence of keyof but it will return ALL keys even field1 which I don't need. So how can I get type with only field2 and field3?

Upvotes: 2

Views: 127

Answers (1)

Aleksey L.
Aleksey L.

Reputation: 38046

You could create mapped type that checks if value extends MyType and if yes takes the key otherwise puts never, then index into it with all possible keys (to produce a union of keys that their values extend MyType):

type PickKeysOfType<T, TValue> = {
    [P in keyof T]: T[P] extends TValue ? P : never
}[keyof T];

type MyTypeKeys = PickKeysOfType<MyInterface, MyType> // "field2" | "field3"

Playground

Upvotes: 1

Related Questions