在 TypeScript 中使用“Extract”实用程序类型的最佳方法
由 Mux 赞助的 DEV 全球展示挑战赛:展示你的项目!
Extract是一个实用类型Typescript,允许您通过提取现有类型的子集来创建新类型。
本文的灵感来源于以下文章Matt Pocock:
Extract以下是一些可能的用法Typescript:
目录
- 加入工会
- 从工会招募多名成员
- 加入一个受歧视的工会
- 争取让多个受歧视工会的成员加入。
- 通过某种方式获得受歧视工会的成员。
- 按类型获取成员
- 从联合体中获取包含子字符串的字符串
- 从联合体中获取具有多个可能值之一的字符串。
- 结论
加入工会
union我们可以使用.提取成员Extract。第一个参数是完整的并集,第二个参数是我们想要获取的并集成员。
type Animal = "cat" | "dog" | "bird" | "fish";
type OnlyCat = Extract<Animal, "cat">; // 'cat'
从工会招募多名成员
Extract我们甚至可以使用以下方法从工会中获取多个成员:
type Animal = "cat" | "dog" | "bird" | "fish";
type ExtractType = Extract<Animal, "cat" | "dog">; // 'cat' | 'dog
即使我们传递一个Extract联合体中不存在的值,Typescript 也会返回联合体中存在的值。
type Animal = "cat" | "dog" | "bird" | "fish";
type ExtractType = Extract<Animal, "cat" | "dog" | "tiger">; // 'cat' | 'dog'
加入一个受歧视的工会
type Shape =
| {
type: 'square'
}
| {
type: 'circle'
}
| {
type: 'triangle'
}
可区分联合类型是指每个成员都具有判别属性的类型。判别属性是可用于区分其他成员的公共属性。在上面的例子中,该type属性用于区分不同的形状。
Extract我们可以使用以下方法提取受歧视工会的成员:
type SqaureShape = Extract<Shape, {type: 'square'}> // { type: 'square' }
争取让多个受歧视工会的成员加入。
我们还可以提取出受歧视工会的多个成员:
type SqaureAndCircleShape = Extract<Shape, {type: 'square'} | {type: 'circle'}>
// { type: 'square' } | { type: 'circle' }
即使工会成员名下还有其他财产,这种方法也适用。
type Shape =
| {
type: 'square';
size: number;
}
| {
type: 'circle'
}
| {
type: 'triangle'
}
type SqaureAndCircleShape = Extract<Shape, {type: 'square'} | {type: 'circle'}>
// {type: 'square'; size: number;} | { type: 'circle' }
union您还可以通过向该属性传递 a 来获得受歧视工会的多个成员type:
type Shape =
| {
type: 'square';
size: number;
}
| {
type: 'circle'
}
| {
type: 'triangle'
}
type SqaureAndCircleShape = Extract<Shape, {type: 'square' | 'circle'}>
// {type: 'square'; size: number;} | { type: 'circle' }
通过某种方式获得受歧视工会的成员。
type Routes =
| {
route: '/user'
search: {
id: string
}
}
| {
route: '/user/create'
}
| {
route: '/user/edit'
search: {
id: string
}
}
type RoutesWithSearch = Extract<
Routes,
{
search: any
}
>
/*
{
route: '/user';
search: {
id: string;
};
} | {
route: '/user/edit';
search: {
id: string;
};
}
*/
要获取联合体的成员,你不一定需要在第二个参数中包含discriminator(在本例中为)成员。你可以直接传递你想获取的成员的名称。routeshape
在这种情况下,我们希望从 Routes 联合类型中提取具有 search 属性的类型。
按类型获取成员
type allTypes = 'admin' | 'user' | 5 | 6 | 7 | true
type onlyNumbers = Extract<allTypes, number> // 5 | 6 | 7
在上面的例子中,我们从联合体中移除了所有不属于数字类型的字面量allTypes。因此,我们最终只得到数字。
从联合体中获取包含子字符串的字符串
type keys = 'userId' | 'tweetId' | 'userName' | 'tweetName'
type UserKey = Extract<keys, `${'user'}${string}`> // "userId" | "userName"
生成的UserKey类型将是字符串“user”开头的所有字符串字面量的并集。这种情况只包含userId字符串userName字面量。
从联合体中获取具有多个可能值之一的字符串。
type keys = 'userId' | 'tweetId' | 'id' | 'userName' | 'friendName'
type OnlyIdKey = Extract<keys, `${string}${'id' | 'Id'}${string}`>
// "userId" | "tweetId" | "id"
您还可以使用Extract它从联合体中获取包含多个可能子字符串之一的所有字符串。
在这种情况下,生成的OnlyIdKey类型将是包含“或”的union字符串字面量。这种情况将包括“ 、”和字符串字面量。keysidIduserIdtweetIdid
结论
好了,各位,就到这里吧。希望这篇文章对你们有所帮助。Extract这是一个用途广泛的实用工具类型。如果你觉得它还有其他用途,Extract,请在评论区告诉我。感谢阅读本文。我们下篇文章再见🐸。