【发布时间】:2020-06-07 13:08:44
【问题描述】:
我有一个变量,它最初是一种类型,IPerson[],但在映射了几次之后,应该添加一个_id 属性,就像Array<IPerson & IWithId>。但是,在倒数第四行中,打印_id 属性会给我一个TS 错误,即使该属性确实存在并且日志记录工作如我所料,打印三个属性fname, lname 和 _id。
我想也许我需要以某种方式重新投射它,比如
mapped = collection.map(mapperB) as Array<IPerson & IWithId>
这没有用,幸好,对于一个 imo 应该已经根据 mapperB 函数的返回类型获取其类型的变量,这样做似乎非常冗长。
let _id = 0;
interface IPerson {
fname: string;
lname: string;
}
interface IWithId {
_id: number;
}
function getNumber() {
return _id++
}
async function getData(json: string): Promise<IPerson[]> {
return JSON.parse(json)
}
function mapperA(entry: IPerson): IPerson {
return {
...entry,
lname: entry.lname.toUpperCase()
}
}
function mapperB(entry: IPerson): IPerson & IWithId {
const _id = getNumber();
return {
...entry,
_id
}
}
async function main() {
const json = `[{"fname":"john","lname":"doe"},{"fname":"jane","lname":"doe"}]`
const collection = await getData(json)
let mapped = collection.map(mapperA)
mapped = collection.map(mapperB)
console.log(mapped[0]._id); // Property '_id' does not exist on type 'IPerson'.
return mapped;
}
main().then(console.log)
如果我使用另一个变量来保存第二个映射函数的值,即const mapped2 = collection.map(mapperB),我可以让它工作,但我很好奇为什么我不能使用我的原始变量?
为什么打字稿不从mapperB的明确声明的返回值推断mapped的值?我可以让它为我做这件事吗?
【问题讨论】:
-
以下关于无法更改变量类型的答案是正确的,但您仍然可以通过链接调用来使用单个变量,如果这就是您所追求的:
let mapped = collection.map(mapperA).map(mapperB)。结果是(IPerson & IWithId)[]
标签: javascript typescript