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' }))
我知道Typescript无法确定类型,因为它是在回调函数中返回的。但是,什么是最不冗长的方式获得良好的类型检查?
[].map 它的设计允许您更改类型,因此它不知道您的意图是返回 MyType . 你可以告诉它:
[].map
MyType
const result = instanceList.map((h): MyType =>({ ...h, replaceThisPropp:'Oops' // now errors. }))