5 concepts · 10 practice questions
TypeScript checks shapes, not names: a value fits a type if it has the required properties with compatible types, whatever it was declared as. Two type aliases with the same shape are interchangeable. A fresh object literal passed straight to a typed slot gets an extra check for unknown properties, which catches typos; a variable holding the same object does not. To keep two same-shaped types apart (a UserId and an OrderId that are both strings), add a brand.
type Point = { x: number };
function draw(p: Point) {}
draw({ x: 1, y: 2 }); // error: 'y' does not exist in type 'Point'
const p = { x: 1, y: 2 };
draw(p); // fine: p has at least the shape of Point
type UserId = string & { readonly __brand: "UserId" };
type OrderId = string & { readonly __brand: "OrderId" };
Sign in to read the rest and take the 10-question test.
Sign in to continue