【发布时间】:2021-02-06 20:06:24
【问题描述】:
Typescript 在尝试将具有可选属性的类型作为可索引类型传递时抛出错误:(Playground)
type Thing = {
thing1?: string
thing2?: string
thing3?: number
}
const thing: Thing = {}
function processObject (obj: { [key: string]: string | number }): string {
/* Generic object handler, not specifically for Thing */
return "test"
}
console.assert(processObject(thing) === "test")
这会导致:
错误:'Thing' 类型的参数不可分配给'{ [key: string]: string | 类型的参数数字; }'。属性“thing1”与索引签名不兼容。键入'字符串 | undefined' 不可分配给类型 'string |数字'。类型“未定义”不可分配给类型“字符串 |号”。
当然,如果参数的类型被强制设为可选,它会起作用:
function processObject (obj: { [key: string]: string | number | undefined }): string {
return "test"
}
不过,我不明白为什么这是必要的。根据TS PR #7029,可索引类型应该与具有相同隐式索引签名的其他类型兼容。
这些属性是否是可选的无关紧要-该属性根本不应该出现在对象上-对吗?为什么我必须指定undefined?有没有更好的方法来做到这一点?
【问题讨论】:
标签: typescript