【TypeScript】TypeScript高级类型之Partial
Partial
Partial 可以快速把某个接口类型中定义的所有属性变成可选的。
举个栗子:
interface ApiKey {
id: number;
name: string;
}
const dataType1: ApiKey = {
id: 1,
name: 'static'
}
const dataType2: ApiKey = {
name: 'json'
}
这段代码会在编译报错:
error TS2741: Property 'id' is missing in type '{ name: string; }' but required in type 'ApiKey'.Key'.
因为dataType2
的类型是ApiKey,ApiKey中id
和name
都是必选的,这导致编译报错。假如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