Initially, I have a variable of type IPerson[]
, but after undergoing a couple of mapping iterations, it should have an added _id
property, transforming it into
Array<IPerson & IWithId>
. However, upon trying to access the _id
property in the fourth-to-last line, TypeScript throws an error even though the property is present, and logging works correctly by displaying the properties fname
, lname
, and _id
.
I tried re-casting it like this:
mapped = collection.map(mapperB) as Array<IPerson & IWithId>
Unfortunately, it didn't work, and it seems overly verbose to have to manually specify the type when it should ideally be inferred based on the return type of the mapperB
function.
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)
I managed to make it work by using a separate variable to store the result of the second mapping function, like
const mapped2 = collection.map(mapperB)
, but I'm puzzled as to why I can't simply use the original variable?