我在使用打字本2.9.1。我的问题的例子:
type MyType = {
replaceThisProp: string
}
const instance:MyType = {
replaceThisProp: 'hello',
}
const instanceList:MyType[] = [instance]
// Misspelling the property here causes an error:
const updatedInstance:MyType = {
...instance,
replaceThisPropp:'Oops'
}
// But here no error is given:
const result: MyType[] = instanceList.map<MyType>(h =>({
...h,
replaceThisPropp:'Oops'
}))我知道类型记录不能确定类型,因为它是在回调函数中返回的。但是,得到好的类型检查最简单的方法是什么呢?
发布于 2018-10-10 09:13:50
[].map是为允许您更改类型而设计的,因此它不知道您的目的是返回MyType。你可以说:
const result = instanceList.map((h): MyType =>({
...h,
replaceThisPropp:'Oops' // now errors.
}))https://stackoverflow.com/questions/52736314
复制相似问题