I am currently working on a Mongoify
type that accepts a type T
, removes the id
key, and replaces it with an _id
key.
type Mongoify<T extends {id: string}> = Omit<T, "id"> & {
_id: ObjectId
};
function fromMongo<T extends { id: string }>(x: Mongoify<T>): T {
const { _id, ...theRest } = x;
const withNormalId = { ...theRest, id: _id.toHexString() };
return withNormalId
}
Unfortunately, I am encountering an issue where this function is not passing the type check. The error message reads:
Type 'Omit<Mongoify<T>, "_id"> & { id: string; }' is not assignable to type 'T'.
'Omit<Mongoify<T>, "_id"> & { id: string; }' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '{ id: string; }'.(2322)
I have reviewed a resource on Stack Overflow (https://stackoverflow.com/questions/56505560/how-to-fix-ts2322-could-be-instantiated-with-a-different-subtype-of-constraint) explaining the TS2322 error, but I am still unclear on the root cause in this scenario. It seems like Typescript may be failing to infer that ...theRest
is of type
Omit<Mongoify<T>, "_id"
, despite the correct type being displayed when inspecting the value in the playground.
If anyone has insights on why this function is failing to pass the typecheck, I would greatly appreciate the assistance.