Search code examples
typescriptgenericsunion-types

Typescript generic of union type: find out type of property from other property


I have a union type with payload and type properties, from which type us uniq. I would like to infer the payload type when given the type.

type AAction = {type: 'A', payload: APayload};
type BAction = {type: 'B', payload: BPayload};

type APayload = number;
type BPayload = string;

type Actions = AAction | BAction;

const actions: Actions[] = [];

type PayloadOfType<T extends Actions['type']> = ????

type PayloadOfTypeA = PayloadOfType<'A'>;

so the goal is that PayloadOfTypeA would be equal to APayload (or number).

Is this possible?


Solution

  • You can use the conditional type Extract:

    type AAction = {type: 'A', payload: APayload};
    type BAction = {type: 'B', payload: BPayload};
    
    type APayload = number;
    type BPayload = string;
    
    type Actions = AAction | BAction;
    
    const actions: Actions[] = [];
    
    type PayloadOfType<T extends Actions['type']> = Extract<Actions, { type: T }>['payload']
    
    type PayloadOfTypeA = PayloadOfType<'A'>;