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

原创
08/30 12:56
阅读数 14

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的子集

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

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部