likes
comments
collection
share

【TypeScript】TypeScript高级类型之Partial

作者站长头像
站长
· 阅读数 56

Partial

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

举个栗子:

interface ApiKey {
  id: number;
  name: string;
}

const dataType1: ApiKey = {
  id: 1,
  name: 'static'
}

const dataType2: ApiKey = {
  name: 'json'
}

【TypeScript】TypeScript高级类型之Partial

这段代码会在编译报错:

error TS2741: Property 'id' is missing in type '{ name: string; }' but required in type 'ApiKey'.Key'.

因为dataType2的类型是ApiKey,ApiKey中idname都是必选的,这导致编译报错。假如ApiKey中的参数是可选的,那么这个问题就会不复存在,而Partial的作用就在于此,它可以帮助我们把ApiKey中的所有属性都变成可选的。

我们永Partial来重写一下这个栗子:

interface ApiKey {
  id: number;
  name: string;
}

const dataType1: ApiKey = {
  id: 1,
  name: 'static'
}

const dataType2:  Partial<ApiKey> = {
  name: 'json'
}

这个时候在运行,就不会报错了。

转载自:https://juejin.cn/post/7041434020269752356
评论
请登录