[Typescript] Tips: Map over a union type

Mapping over a union type can feel tricky to conceptualise. But actually, TypeScript does it all for you - using Distributive Conditional Types.

Here, we create RemoveC - a type helper to remove c from a union of letters.

export type Letters = 'a' | 'b' | 'c'

// typescript loop through union type, once it found 'c', it will remove it because we return never
// if you replace never with 'd', then final result become 'a' | 'b' | 'd'
type RemoveC<TTYpe> = TType extends 'c' ? never : : TTYpe;

type WithoutC = RemoveC<Letters>; // 'a' | 'b'

 

posted @ 2022-10-18 01:22  Zhentiw  阅读(32)  评论(0)    收藏  举报