类型定义如下
type originType = "剪贴板" | "主动上传"
type Status = "上传成功" | "同步中"
export interface UploadInfo {
addTime: number | Date
finishTime: number | Date
fileName: string
url: string,
mime: string,
status: Status
progress?: number
origin: originType
}
function add(item: Omit<UploadInfo, "finishTime" | "status">) {
const list = this.list.value;
if (list.length > this.opt.max) {
list.pop()
}
const uploadInfo: UploadInfo = {
status: '上传成功',
finishTime: new Date().getTime(),
...item,
}
list.unshift(uploadInfo);
}
运行在使用add方法的时候不传入finishTime和status,因为在后面我给了默认值
但是有想要在主动调用的时候传入status值,ts类型提示不能复制给类型
如果希望
finishTime
和status
可选,可以直接在接口中添加?
声明,就像progress
那样。如果只是希望参数部分属性可选,可以使用
Partial<UploadInfo>
让所有属性都可选。Omit
是去掉指定的属性,并非把这些属性变成可选。题中的错误是因为使用 Literal 对象会严格匹配类型但类型中又没有status
属性造成的如果只是希望产生一个部分属性可选的新类型,可以这么计算
Omit
去掉指定的属性Keys
,得到新类型A
Pick
把Keys
指定的属性剥离出来,得到新类型B
Partial
把剥离出来的属性变成可选,得到新类型B'
A
和B'
,得到想要的结果根据上面的描述可以定义一个新的工具类型
然后,使用
SomePartial
计算出来的类型应该就是你想要的代码示例:TypeScript Playground