Advanced TypeScript Exercises - Question 2
Pragmatic Maciej
Posted on February 11, 2020
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'
}
}
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.
đź’– đź’Ş đź™… đźš©
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
javascript How I Created Vanilla Calendar Pro — A Lightweight and Flexible JavaScript Calendar with TypeScript
November 28, 2024