Cool, it took me a little to figure this one out. I've made a Gist to hold the answer as to not spoil other people!
Gist Here
Anser From Gist:
PD: I don't know if it's the correct answer, but it's what I would have 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.
other
So to solve this we could:
function makeCustomer<T extends User>(u: T): T { return { ...u, id: u.id, kind: 'customer', }; }
User
function makeCustomer<T extends User>(u: T): User { return { id: u.id, kind: 'customer', }; }
as T
function makeCustomer<T extends User>(u: T): T { return { id: u.id, kind: 'customer', } as T; }
Ah, of course.
Mark the output objects as T
I think this is a bad option, as it's possible that you would be now expecting an extra field to be there, that no longer exists.
Agreed, this is why I marked the first option as preferred :P
I think u could also do a ...u inside the return
Mangola, link is broken please fix it :)
Ohh sorry, fixed, I shared the edit link
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Cool, it took me a little to figure this one out. I've made a Gist to hold the answer as to not spoil other people!
Gist Here
Anser From Gist:
PD: I don't know if it's the correct answer, but it's what I would have 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:
If the above Generic is passed, the return type expects to also contain
other
property.So to solve this we could:
User
as T
Ah, of course.
I think this is a bad option, as it's possible that you would be now expecting an extra field to be there, that no longer exists.
Agreed, this is why I marked the first option as preferred :P
I think u could also do a ...u inside the return
Mangola, link is broken please fix it :)
Ohh sorry, fixed, I shared the edit link