Tom Le
Tom Le

Reputation: 127

How can I get specific type in `or` operator definition?

For example I have type like this blow:

type ActionResource = {
    type: "QUERY";
    payload: IListPayload;
} | {
    type: "GET";
    payload: {
        id: string;
    };
} | {
    type: "QUERY_NEXT";
} | {
    type: "SAVE";
    payload: {
        id: string;
        data: any;
    };
} | {
    type: "SEARCH_TEXT";
    payload: {
        ...;
    };
}

Now I would like to get specific type which has type properties = 'SAVE' So I do like this

type GetActionResourceType<K extends ActionResource['type']> = ActionResource
type SaveType = GetActionResourceType<'SAVE'>

I hope it will return type of SaveType look like:

{
    type: "SAVE";
    payload: {
        id: string;
        data: any;
}

How can I make GetActionResourceType in my purpose

Upvotes: 0

Views: 35

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249666

You can just use the Extract (see in docs at Predefined conditional types)conditional type to extract a type that extends a specific type:

type GetActionResourceType<K extends ActionResource['type']> = Extract<ActionResource, { type: K }>

Upvotes: 1

Related Questions