Grokking TypeScript
0% completed
Function Overloading
The shop needs a lookup that returns one product name for one ID and a list of names for a list of IDs. A union type on the parameter and on the return value seems to describe this, but it creates a problem for every caller.
type Product = { id: number; name: string; price: number }; const catalog: Product[] = [ { id: 1, name: "Laptop", price: 1200 }, { id: 2, name: "Phone", price: 800 }, { id: 3, name: "Tablet", price: 500 }, ]; function nameOf(id: number): string { return catalog.find((product) => product.id === id)?.name ?? "Unknown"; }
.....
.....
.....
Like the course? Get enrolled and start learning!
Reading Progress
0%