Sub topic 2
Static types in practice
This chapter assumes you can write JavaScript functions, objects, and modules, and that you can run tsc from a terminal. Installing and configuring the compiler comes in later chapters. For now, paste the examples into the TypeScript Playground or into a project where npx tsc --noEmit works. The goal here is to see what types check, what they don't check, and which mistakes show up most often.
What a static type is
A static type is a label the compiler attaches to a value or variable before the program runs. The compiler uses the labels to reject operations that can't work, such as calling a string method on a number. Checking happens when you run tsc or when your editor analyzes the file, not when the code executes.
JavaScript has types too, but it checks them at runtime. 42.toUpperCase() fails only when that line runs. TypeScript moves that failure to the editor or the build.
Annotating parameters and return values
A type annotation is a colon and a type placed after a name. Annotate function parameters and, usually, return types:
function greet(name: string): string {
return `Hello, ${name}!`;
}
console.log(greet("Ada"));If you add the call greet(42), the compiler reports:
error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'."Assignable" is the key term. TypeScript doesn't ask whether two types are identical. It asks whether a value of one type can be used where the other type is expected. A string can go where a string is expected. A number can't.
Inference: you don't annotate everything
The compiler works out many types from the code around them. This is called type inference.
let total = 0;
const names = ["Ada", "Grace"];
const limit = 10;
total = total + names.length;
console.log(total, limit);Here total is inferred as number, names as string[], and limit as the literal type 10. A const of a primitive gets its exact value as its type, while a let gets the wider type. Assigning total = "many" is an error because total is a number.
A common convention:
- Annotate function parameters. The compiler can't infer them from a plain declaration.
- Annotate return types on exported functions, so the public contract is written down and an accidental change in the body shows up as an error.
- Leave local variables to inference unless the inferred type is wrong or too wide.
Over-annotating isn't harmful, but it adds noise and can hide a more precise inferred type. For example, writing const limit: number = 10 throws away the knowledge that limit is exactly 10.
Describing objects
Real code passes objects around. Use an interface or a type alias to describe their shape:
interface User {
id: number;
name: string;
email?: string;
}
function describe(user: User): string {
const email = user.email ?? "no email";
return `${user.name} <${email}>`;
}
console.log(describe({ id: 1, name: "Ada" }));The ? marks email as optional. Its type is then string | undefined, so you can't use it as a plain string without handling the missing case. That is why the code uses ?? to supply a fallback.
For plain object shapes, interface and type are interchangeable in most situations. Pick one and stay consistent. Differences between them are covered later in the tutorial.
Structural typing
TypeScript compares objects by shape, not by name. Any value with the required properties of the right types satisfies User, whether or not it was created "as a User". This matches how JavaScript code is written, which is why typing existing JavaScript is practical.
One check can look like an exception to this. When you write an object literal directly where a type is expected, the compiler also rejects extra properties:
interface User {
id: number;
name: string;
}
function show(user: User): string {
return `${user.id}: ${user.name}`;
}
const fromForm = { id: 2, name: "Grace", role: "admin" };
console.log(show(fromForm));
// show({ id: 3, name: "Linus", role: "admin" }); // error: 'role' does not exist in type 'User'The call with fromForm compiles because the extra role is allowed when the value comes from a variable. The commented-out call fails the excess property check, which catches typos in option names, for example colour where color was meant. The rule applies only to fresh object literals.
Union types and narrowing
A union type, written with |, means a value can be one of several types:
function formatId(id: number | string): string {
if (typeof id === "string") {
return id.toUpperCase();
}
return id.toFixed(0).padStart(6, "0");
}
console.log(formatId("ab12"));
console.log(formatId(42));Inside the if block, the compiler knows id is a string. After the return, it knows id must be a number. This is narrowing: the compiler follows your control flow and refines a variable's type after checks such as typeof, ===, in, instanceof, and truthiness tests.
Without the check, id.toUpperCase() would be an error, because toUpperCase doesn't exist on number. The compiler requires you to prove which case you are in.
Literal unions
A union of specific values works like a lightweight enum:
type Status = "idle" | "loading" | "done";
function label(status: Status): string {
switch (status) {
case "idle":
return "Waiting";
case "loading":
return "Working...";
case "done":
return "Finished";
}
}
console.log(label("done"));Passing "finished" is a compile error. If you later add "failed" to Status and forget to handle it, the function no longer returns a string on every path, and the compiler reports that. That is a refactoring safety net plain JavaScript can't give you.
The null and undefined problem
Most runtime crashes in JavaScript come from undefined or null being used as if they were real values. TypeScript can track them, but only when strictNullChecks is on. That option is part of strict, which later chapters cover in detail.
function firstLetter(text: string | undefined): string {
return text.charAt(0);
}With strict enabled, this fails:
error TS18048: 'text' is possibly 'undefined'.Without strictNullChecks, undefined is silently allowed in every type, and the error never appears. Check for the missing value and the error goes away:
function firstLetter(text: string | undefined): string {
if (text === undefined) {
return "";
}
return text.charAt(0);
}
console.log(firstLetter("Ada"));
console.log(firstLetter(undefined));You could also write text?.charAt(0) ?? "". Avoid the non-null assertion text!.charAt(0) unless you can prove the value exists. It silences the compiler without adding a runtime check.
any, unknown, and where types stop
any turns off checking for a value. Anything can be assigned to it, and you can do anything with it. It is useful during a gradual migration and harmful as a habit, because one any spreads: values computed from it are also any.
unknown is the safe alternative. Anything can be assigned to it, but you must narrow it before using it. This fits data from outside your program, such as parsed JSON:
function parseAge(raw: string): number {
const data: unknown = JSON.parse(raw);
if (
typeof data === "object" &&
data !== null &&
"age" in data &&
typeof data.age === "number"
) {
return data.age;
}
throw new Error("Payload has no numeric age");
}
console.log(parseAge('{"age": 36}'));The in check narrows data to an object that has an age property, which needs TypeScript 4.9 or later.
The same applies to type assertions. JSON.parse(raw) as User compiles, but nothing verifies the shape. If the data is wrong, you get a runtime failure later and far from the cause, which is the problem you adopted TypeScript to avoid. Treat as as a last resort for facts the compiler can't know, such as the result of document.getElementById("app") as HTMLCanvasElement when you control the markup.
Common errors and what they mean
| Error | Typical message | Usual cause |
|---|---|---|
| TS2345 | Argument of type 'number' is not assignable to parameter of type 'string' | Wrong value passed to a function |
| TS2322 | Type 'string' is not assignable to type 'number' | Assigning or returning the wrong type |
| TS2339 | Property 'x' does not exist on type 'Y' | Typo, or a union not yet narrowed |
| TS7006 | Parameter 'x' implicitly has an 'any' type | Missing parameter annotation (needs `noImplicitAny`, included in `strict`) |
| TS18048 | 'x' is possibly 'undefined' | A nullable value used without a check (needs `strictNullChecks`) |
Read errors from the first line of the message. Multi-line messages explain why an assignment failed, with the most specific mismatch at the bottom. Fix the first error in a file before the others, since one wrong type often causes several follow-on errors.
Practical habits
- Prefer inference for locals and annotate function boundaries.
- Model "might be missing" explicitly with
| undefinedor?, then handle it. - Use
unknown, notany, for data you haven't validated. - Use literal unions in place of loose strings for a fixed set of values.
- Treat every
asand!as a spot where you have overridden the compiler, and keep them few.
Exercise
This function compiles without strict mode but fails with it. Why, and how do you fix it? function shout(message?: string): string { return message.toUpperCase() + "!"; }
Show answer
The optional parameter has type string | undefined. With strictNullChecks (part of strict), calling toUpperCase on it is error TS18048 ("'message' is possibly 'undefined'"). Fix it by handling the missing case, for example: if (message === undefined) { return "!"; } return message.toUpperCase() + "!"; or by giving a default value: function shout(message: string = ""): string.
Exercise
Given interface User { id: number; name: string }, which of these calls to show(user: User) fails the excess property check, and why does the other one compile? (a) show({ id: 1, name: "Ada", admin: true }) (b) const u = { id: 1, name: "Ada", admin: true }; show(u)
Show answer
Call (a) fails because a fresh object literal passed directly where a User is expected may not contain properties that User doesn't declare, so 'admin' is reported. Call (b) compiles because u is a variable, not a fresh literal. The excess property check doesn't apply, and u still has every property User requires (structural typing).