首先有这么个人员接口

interface IInfo {
  name: string; // 姓名
  age: number; // 年龄
  height: string; // 身高
  phone: string; // 联系电话
  email: string; // 邮箱
}

1. Omit

Omit类型可以从一个对象类型中 忽略某些属性 

假设我们使用IInfo接口,但是不想要其中phone和email字段,就可以采用Omit,具体如下 

type OmitPhoneEmailInfo = Omit<IInfo, 'phone' | 'email'>
// 类型如下
OmitPhoneEmailInfo {
  name: string; // 姓名
  age: number; // 年龄
  height: string; // 身高
}

2. Pick

Pick类型可以从一个对象类型中 取出某些属性 

假设我们使用IInfo接口,某些场景下,我们只需要其中的name和age属性,其他都不需要,当然我们可以重新再写个接口,但是这样在将来维护起来并不好,因为我们后面所有用的属性接口都应该是由IInfo接口推导出来的,那么就可以使用Pick来解决

type PickNameAgeInfo = Pick<IInfo, 'name' | 'age'>
// 类型如下
PickNameAgeInfo {
  name: string; // 姓名
  age: number; // 年龄
}

3. Partial

Partial类型可以快速把某个接口类型中定义的属性变成可选的 

type PartialInfo = Partial<IInfo>
// 等价于
PartialInfo {
  name?: string; // 姓名
  age?: number; // 年龄
  height?: string; // 身高
  phone?: string; // 联系电话
  email?: string; // 邮箱
}

4. Required

Required可以将接口中的所有可选项变为必选项

interface IArticle {
  title?: string;
  content?: string;
  author?: string;
  date?: string | Date;
}

type RequiredArticle = Required<IArticle>

// 等价于
RequiredArticle {
  title: string;
  content: string;
  author: string;
  date: string | Date;
}

5. 简单示例

 这个示例用到了上面的Omit、Pick和Partial。Required也是一样的,真正用到的时候能想到就行。

现在我们需要写一个创建文章的函数,返回文章对象,文章类型如下:

interface IArticle {
  title: string; // 文章标题
  content: string; // 文章内容
  author: string; // 作者
  date: string | number | Date; // 时间
}

也就是说我们的文章对象是必须包含上面四个属性的,但是我们创建文章时可以不传递作者和时间,如果不传,我们就默认作者为匿名,时间为当前时间。也就是说传递的参数是下面这个类型:

interface ICreateArticle {
  title: string; // 文章标题
  content: string; // 文章内容
  author?: string; // 作者
  date?: string | number | Date; // 时间
}

当然我们可以像上面似的将这两个约束对象都写出来,但是这样 麻烦是一方面,另一方就是维护的时候也可能出问题,况且也不好,因为我们下面的类型其实是由上面的类型推导出来的。这时候我们可以使用Omit、Pick和Partial来实现,将IArticle拆分一下然后取并集即可:

TypeScript中的Omit、Pick、Partial、Required类型_并集

 具体实现如下:

interface IArticle {
  title: string; // 文章标题
  content: string; // 文章内容
  author: string; // 作者
  date: string | Date | number; // 时间
}

type Optional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>

// 创建文章
function createArticle(article: Optional<IArticle, 'author' | 'date'>): IArticle {
  const { title, content } = article
  const author = article.author ?? '匿名'
  const date = article.date ?? new Date().getTime()
  return { title, content, author, date }
}