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

08/30 12:56

https://juejin.im/post/6865910915011706887

# Extract / SetIntersection 求交集

``````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 求差集

``````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

``````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