links

Exclude<T, U> 从 T 中剔除可以赋值给 U 的类型。

1. 基本使用

type Name = 'Yang' | 'Li' | 'Wang';
type Result = Exclude<Name, 'Wang'>; // "Yang" | "Li"

2.移除多个

type Name = 'Yang' | 'Li' | 'Wang';
type Result = Exclude<Name, 'Wang' | 'Li'>; // "Yang"

3.移除联合对象类型

type Name = { name: 'Yang'; age: 18 } | { name: 'Li'; age: 18 } | { name: 'Wang'; age: 80 };
type Result = Exclude<Name, { age: 80 }>; // { name: 'Yang', age: 18 } | { name: 'Li', age: 18 }

4. 移除联合对象类型中包含某个属性的类型

// 通过 exclude {search: any} 来排除所有具有 search 属性的对象类型
type Router =
	| { path: '/user' }
	 | { path: '/home' }
	 | { path: '/login'; search: string }
	| { path: '/log'; search: { params: string } };
type Result = Exclude<Router, { search: any }>; // { path: '/user' } | { path: '/home' }

5. 从联合类型中删除字符串/数字/布尔

type Name = 'Yang' | 18 | true;
type Result = Exclude<Name, boolean>; // "Yang" | 18
type Result2 = Exclude<Name, number | boolean>; // "Yang"

6. 从联合联合类型中删除包含子字符串的字符串类型

type ObjectKey = 'userId' | 'postId' | 'userName' | 'postName';
type Result = Exclude<ObjectKey, `${string}${'user'}${string}`>; // "postId" | "postName"

7. 从联合类型中删除多个可能值之一的字符串

type ObjectKey = 'userId' | 'postId' | 'id' | 'userName' | 'postName';
type Result = Exclude<ObjectKey, `${string}${'id' | 'Id'}${string}`>;  // "userName" | "postName"

8. 从联合类型中删除包含特定前缀/后缀的字符串类型

type ObjectKey = 'userId' | 'postId' | 'id' | 'userName' | 'postName';
type Result = Exclude<ObjectKey, `${'user' | 'post'}${string}`>; // "id"
type Result = Exclude<ObjectKey, `${string}Name`>; // "userId" | "postId" | "id" // 匹配后缀
type Result = Exclude<ObjectKey, `post${string}`>; // "id" | "userId" | "userName" // 匹配前缀