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.