• 欢迎光临~

[Typescript] Tips: Map over a union type

开发技术 开发技术 2022-10-18 次浏览

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'

 

程序员灯塔
转载请注明原文链接:[Typescript] Tips: Map over a union type
喜欢 (0)
违法和不良信息举报电话:022-22558618 举报邮箱:dljd@tidljd.com