ts utility-types ​​​​​​​ 源码解读 Union operators

原文链接: ts utility-types 源码解读 Union operators

上一篇: ts utility-types ​​​​​​​ 源码解读 aliases-and-guards

下一篇: ts utility-types ​​​​​​​ 源码解读 Special operators

https://juejin.im/post/6865910915011706887

Extract / SetIntersection 求交集

从类型A中获取可兼容类型B的类型, 一般用于联合类型

条件类型作用于联合类型会变成分布式条件类型, 所以会逐一判断A中的每一个类型是不是B的子类型, 然后将结果为真的类型作为联合类型返回

type SetIntersection<A, B> = A extends B ? A : never;
type Extract<T, U> = T extends U ? T : never;

type t1 = "a" | "b" | "c";
type t2 = "b" | "c" | "d";


// 两个都是 'b' | 'c'
type t3 = Extract<t1, t2>;
type t4 = SetIntersection<t1, t2>;

Exclude /  SetDifference 求差集

类似集合中的A-B, 在A中去除不兼容B的类型

type SetDifference<A, B> = A extends B ? never : A;
type Exclude<T, U> = T extends U ? never : T;

type t1 = "a" | "b" | "c";
type t2 = "b" | "c" | "d";

// 两个都是 'a'
type t3 = SetDifference<t1, t2>;
type t4 = Exclude<t1, t2>;

SetComplement

求补集, 限制B必须是A的子集

up-13549d9f187fa562e30818e5c9aa96386c3.png
type SetDifference<A, B> = A extends B ? never : A;
type SetComplement<A, A1 extends A> = SetDifference<A, A1>;

type t1 = "a" | "b" | "c";
type t2 = "b" | "c" | "d";

// t3 = 'a' , t4 报错
type t3 = SetDifference<t1, t2>;
type t4 = SetComplement<t1, t2>;

SymmetricDifference 交叉补

A并B - A交B

type SetDifference<A, B> = A extends B ? never : A;
type SymmetricDifference<A, B> = SetDifference<A | B, A & B>;

type t1 = "a" | "b" | "c";
type t2 = "b" | "c" | "d";

// 'a' | 'd'
type t4 = SymmetricDifference<t1, t2>;

NonNullable / NonUndefined 过滤null和undefined

tsconfig.json中将 strictNullChecks 设置为true,严格来检查null类型,如果不开启的话ts就默认undefined与null是兼容的,所以就会将null类型一起过滤掉。

type NonUndefined<A> = A extends undefined ? never : A;
type NonNullable<T> = T extends null | undefined ? never : T;

type t1 = "a" | "b" | "c" | null | undefined;

type t3 = NonNullable<t1>; // 'a' | 'b' | 'c'
type t4 = NonUndefined<t1>; // 'a' | 'b' | 'c' | null

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值