TypeScript for Real Projects · 18 min · 100 XP
Annotations and inference
Let TypeScript infer the obvious types, annotate important boundaries, and describe object shapes without duplicating information.
Prerequisites: JavaScript functions, objects, arrays and promises; React basics for the props lesson. Predict each recall answer, then solve the challenge before opening its hint. The exercise runner strips types and checks behavior; it does not run the type checker. For static feedback, copy your code into a local TypeScript project and run tsc --noEmit as taught in the compiler lesson. No imports or JSX are needed in these exercises.
TypeScript is JavaScript plus a static type checker. The checker studies your code before it runs and points out operations that do not fit the types it knows. The types disappear from the JavaScript you ship, so they prevent mistakes during development rather than validating live user data at runtime.
const taxRate = 0.13; // inferred as number
function total(price: number, quantity: number): number {
return price * quantity * (1 + taxRate);
}
const amount = total(20, 2); // amount is inferred as numberUse inference when the answer is obvious. Writing const count: number = 3 repeats what 3 already says. Add annotations at boundaries: function parameters, public return values, API data after validation, component props, and empty collections whose contents cannot be inferred. Hovering a value in a TypeScript-aware editor shows what the compiler inferred.
interface User {
readonly id: string;
name: string;
nickname?: string;
}
function displayName(user: User): string {
return user.nickname ?? user.name;
}
displayName({ id: "u1", name: "Mina" }); // "Mina"any turns checking off and lets mistakes spread. When a value really is unknown (JSON, local storage, a message from another system), start with unknown, check what it is, and only then use it.
Loading your workspace…