2

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.