打字稿:如何在映射列表时进行类型检查
Typescript: How to get typechecking while mapping over a list
我正在使用 Typescript 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'
}))
我了解到 Typescript 无法确定回调函数中返回的类型。但是,获得良好类型检查的最不冗长的方法是什么?
[].map
的目的是让你改变类型,所以它不知道你的意图是returnMyType
。你可以告诉它:
const result = instanceList.map((h)<strong>: MyType</strong> =>({
...h,
replaceThisPropp:'Oops' // now errors.
}))
我正在使用 Typescript 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'
}))
我了解到 Typescript 无法确定回调函数中返回的类型。但是,获得良好类型检查的最不冗长的方法是什么?
[].map
的目的是让你改变类型,所以它不知道你的意图是returnMyType
。你可以告诉它:
const result = instanceList.map((h)<strong>: MyType</strong> =>({
...h,
replaceThisPropp:'Oops' // now errors.
}))