Skip to content

Instantly share code, notes, and snippets.

@nombrekeff
Last active February 11, 2020 11:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nombrekeff/e64480b644ac83fc9f82d7510050ca02 to your computer and use it in GitHub Desktop.
Save nombrekeff/e64480b644ac83fc9f82d7510050ca02 to your computer and use it in GitHub Desktop.
Gist for "Advanced TypeScript Exercises - Question 2"

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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment