PD: I don't know if it's the correct answer, but it's what I would of done :)
I think it fails because we always expect the output type to be equal to the generic type, although we always return a User.
Typescript tells us that if we pass in a generic type, for example:
createCustomer<{ id: number, kind: string, other: number }>({
id: 1,
kind: 'customer'
});
// >> This gives an error, "Property 'other' is missing in type"
If the above Generic is passed, the return type expects to also contain other
property.
So to solve this we could:
- Pass in all additional parameters to return (preferred)
function makeCustomer<T extends User>(u: T): T {
return {
...u,
id: u.id,
kind: 'customer',
};
}
- Set the return type always to
User
function makeCustomer<T extends User>(u: T): User {
return {
id: u.id,
kind: 'customer',
};
}
- Mark the output objects
as T
function makeCustomer<T extends User>(u: T): T {
return {
id: u.id,
kind: 'customer',
} as T;
}