Advanced TypeScript Exercises - Question 2

macsikora

Pragmatic Maciej

Posted on February 11, 2020

Advanced TypeScript Exercises - Question 2

In this question I will ask you, why TS fails here. And I can say there is a valid reason why such construct is wrong, its not a language bug. Can you spot why, and what is example type which proves TypeScript rightly prevents such code to compile?

type User = {
  id: number;
  kind: string;
};

function makeCustomer<T extends User>(u: T): T {
  // Below error, why?
  return {
    id: u.id,
    kind: 'customer'
  }
}
Enter fullscreen mode Exit fullscreen mode

You can start playing with this code here - Playground link.
Post your answers in comments. Have fun! Answer will be published soon!

This series is just starting. If you want to know about new exciting questions from advanced TypeScript please follow me on dev.to and twitter.

đź’– đź’Ş đź™… đźš©
macsikora
Pragmatic Maciej

Posted on February 11, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related