Typescript 实用程序类型
介绍
当我开始认真学习 Typescript 时,我遇到了一组实用类型,当我尝试重构我们所在公司的代码库中的类型时,它们被证明是有用的。
在此之前,我假设为了重用类型代码,我必须制作粒度类型并将它们导出到字段中需要它们的每个类型。
例如,如果我有一个Person
类型,并且要在某个Parent
类型或某个Child
类型中使用,我必须创建它,然后将其导出并使用它。当然,这只是一个简单的例子。当我们在组件之间共享大量类型时,我们就会发现,每次尝试使用该类型时都导入该类型会变得多么繁琐。
来看看实用程序类型。这些实用程序旨在消除重复定义和导入每个函数的问题。我想介绍一些我觉得有用的实用程序。
实用工具
挑选
当我们想要重用或“挑选”类型中的某些属性时,我们会使用Pick
。这非常有用,因为它节省了我创建新类型的时间,而这些时间仅仅是复制现有类型的属性。
interface Workstation {
CPU: string
GPU: string
RAM: string
monitor: string
keyboard: monitor
}
type Computer = Pick<Workstation, 'CPU' | 'GPU' | 'RAM'>
部分的
当我们想让某种类型的属性成为可选属性时,我们会使用Partial
。这在重构时很有用。
interface Car {
wheels: string
windshield: string
body: string
doors: string
}
type Car2 = Partial<Car>
必需的
另一方面,如果我们想让某种类型的属性成为必需的,我们会使用Required
。这有助于强制基于外部库类型的类型。
interface OptionalParams {
a?: string
b?: string
}
type RequiredParams = Required<OptionalParams>
记录
在构建配置类型时非常有用。
interface Person {
name: string
}
type Family = ‘father’ | ‘mother’ | ‘sibling’
const myFamily: <Family, Person> = {
father: { name: ‘John’ },
mother: { name: ‘Jane’ },
sibling: { name: ‘Joe’ }
}
忽略
对于获取类型的精简版本非常有用
interface Article {
title: string;
summary: string;
text: string;
}
type ArticlePreview = Omit<Article, text>;
const todo: ArticlePreview = {
title: ‘The misadventures of Joe’,
summary: ‘Joe goes out of his way to explore. Will he survive?’
};
排除
基本上是两个集合的“补集”
type Toys = Exclude<“knife” | “ball” | “xylophone”, “knife”>; // “ball” | “xylophone”
提炼
基本上是两个集合的“交集”
type Vehicle = Extract<“skateboard” | “car” | “motorbike”, “car” | “motorbike” | “wheelchair”>; // “car” | “motorbike”
结论
在我不断学习 Typescript 并将其融入代码的过程中,我发现这些实用类型用得越来越多。只要不过度使用,它们就能让我的代码更简洁易懂。希望你们也觉得它们有用。
鏂囩珷鏉ユ簮锛�https://dev.to/developarvin/typescript-utility-types-4ble