Home > Enterprise >  How can I get object keys from this union type?
How can I get object keys from this union type?

Time:08-18

I am just wondering how can I get keys form this union type.

Value is getting never type.

I want Value to be sno | key | id

type Key = { sno: number } | { key: number } | { id: number };
type Value = keyof Key;

CodePudding user response:

Utilizing (or rather, abusing) conditional types, we get:

type Key = { sno: number } | { key: number } | { id: number };

type Value = Key extends infer T ? T extends T ? keyof T : never : never;

You can read a little more about this behavior here (distributive conditional types).

Before we do that though, we use Key extends infer T to put Key into a naked generic type.

  • Related