【TypeScript】TypeScript高级类型之Partial

Partial

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

举个栗子:

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

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

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

image.png

这段代码会在编译时报错:

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'
}

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

猜你喜欢

转载自blog.csdn.net/weixin_43853746/article/details/121923864