Home > Back-end >  How can I get the keys from an object that is union as shared?
How can I get the keys from an object that is union as shared?

Time:08-18

For example

If I take this Type and put it in keyof, I get never.

type T = {
        items?: string[] | undefined;
        'items.0.kind'?: string[] | undefined;
        'items.0.institution'?: string[] | undefined;
        'items.0.started_at'?: string[] | undefined;
        'items.0.finished_at'?: string[] | undefined;
        'items.0.specialization'?: string[] | undefined;
        'items.0.qualification'?: string[] | undefined;
    } | {
        user_is_blocked?: string[] | undefined;
        jwt_token_is_invalid?: string[] | undefined;
        jwt_token_is_expired?: string[] | undefined;
    }
type Keys = keyof T // === never

CodePudding user response:

You can use a conditional distributive type to operate on parts of a union:

type T = {
        items?: string[] | undefined;
        'items.0.kind'?: string[] | undefined;
        'items.0.institution'?: string[] | undefined;
        'items.0.started_at'?: string[] | undefined;
        'items.0.finished_at'?: string[] | undefined;
        'items.0.specialization'?: string[] | undefined;
        'items.0.qualification'?: string[] | undefined;
    } | {
        user_is_blocked?: string[] | undefined;
        jwt_token_is_invalid?: string[] | undefined;
        jwt_token_is_expired?: string[] | undefined;
    }

type Distributive<T> = T extends any ? keyof T: never
type Keys = Distributive<T> 
  • Related