I have a type Mongoify that takes in a type T and removes the id key and replaces it with a _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
}
For some reason, this function does not type check. I get the error:
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 looked at How to fix TS2322: "could be instantiated with a different subtype of constraint 'object'"?, which explains what is going on with this error. But I'm not sure what the cause is here. My assumption is Typescript is failing to do the type inference that ...theRest is of type Omit<Mongoify<T>, "_id">, but even that seems incorrect because if I mouse over the value in the playground, Typescript shows me the correct type.
Anyone know why this function is failing to typecheck?