I’m using mongodb and planning to have a generic util function that maps the _id
field to id
.
const mapId = <T extends { _id?: string }>(item: T) => {
const { _id, ...rest } = item;
if (_id === undefined) {
return rest;
}
return { ...rest, id: _id };
}
The rationale is that Mongodb queries have projection, hence the _id
field might or might not be present. If it exists, then map it to id
.
However, when I invoked this function, I got a typescript error
const city = { _id: 'new-york', name: 'New York' };
const mappedCity = mapId(city);
console.log(mappedCity.id); // has typescript error
The typescript error says Property 'id' does not exist on type 'Omit<{ _id: string; name: string; }, "_id">'.
I also checked that mapId somehow has the following type,
const mapId: <T extends {
_id?: string | undefined;
}>(item: T) => Omit<T, "_id">
which does not incorporate the id
field created in the mapId
function. Why does it behave this way? How should I write the util function typings?