TypeScript Creating Union Type from a Union Type

type TodoAction =
    | { type: 'INIT' }
    | { type: 'ADD_TODO', text: string }
    | { type: 'REMOVE_TODO', id: string }
    | { type: 'SET_COMPLETED', id: string };
type KeysOfUnion<T extends { type: any }> = 
   T extends { type: infer K } ? {} extends Omit<Extract<T, { type: K }>, 'type'> ? never : K : never;

function dispatch(actionType: KeysOfUnion<TodoAction>) { throw new Error('Not implemented') };

dispatch('ADD_TODO');

Better usage

type KeysOfUnion<T extends { type: any }> = 
   T extends any ? {} extends Omit<T, 'type'> ? never : T['type'] : never;

function dispatch(actionType: KeysOfUnion<TodoAction>) { throw new Error('Not implemented') };

dispatch('ADD_TODO');

Leave a Reply