首页 > 其他分享 >[Typescript] Tips: Map over a union type

[Typescript] Tips: Map over a union type

时间:2022-10-18 01:33:06浏览次数:43  
标签:Map Typescript union RemoveC over never Tips 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'

 

标签:Map,Typescript,union,RemoveC,over,never,Tips,type
From: https://www.cnblogs.com/Answer1215/p/16801256.html

相关文章