我有一个变量,它从一个类型开始,但是在映射了几次之后,应该添加一个属性,就像.但是,在倒数第四行中,打印属性的附加项会给我一个 TS 错误,即使该属性确实存在并且日志记录的工作方式与我预期的一样,打印三个属性 、 和 。IPerson[]_idArray<IPerson & IWithId>_idfnamelname_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)
如果我使用另一个变量来保存第二个map函数的值,我可以让它工作,即我很好奇为什么我不能使用我的原始变量?const mapped2 = collection.map(mapperB)
为什么类型脚本不从显式声明的返回值中推断出 的值?我可以让它为我做这件事吗?mappedmapperB
慕的地8271018
隔江千里
拉莫斯之舞
相关分类