liveBook · Manning

Static typing

As explained in React in Depth

A static type is a type assigned and checked during program analysis before the code executes.

Static typing lets TypeScript check whether values fit their intended uses before code runs. The result is still JavaScript: transpilation removes TypeScript’s additional type features, but type mismatches can be caught during development. In React applications, this helps make component contracts more reliable and easier to maintain. section 5.1 section 5.4

Annotate the boundary

A function that adds two values gives the type checker little to work with when its parameters have implicit `any` types. Define `function fibonacci(a: number, b: number) { return a + b; }` and a call with `true` or a string produces an argument-type error. Valid numeric calls also let TypeScript infer that the result is a number; the caller need not annotate every variable. section 5.2.2

const f0 = 0;
const f1 = 1;
const f2 = fibonacci(f0, f1);
const f3 = fibonacci(f1, f2);

The successive calls show inference carrying numeric types from initial values through the function’s results. section 5.2.2

Use explicit types where they define a useful contract, then let inference handle values it can determine:

  • Use a union such as `null | string` when a value may have either type; use a literal union to restrict a status to named values and reject an unlisted one. section 5.2.2
  • Define React component props with a type or interface, including optional properties where appropriate. section 5.2.2 section 5.4

Annotations are most valuable at boundaries such as function parameters and component props; inference avoids repeating types that TypeScript already knows. This is a way to catch mismatches earlier, not a reason to annotate every expression. section 5.2.2 section 5.4

How React in Depth covers it

How deep it goes
Works through parameter annotations, inference, unions, and component props, but does not detail type-checker internals.
Examples
Tests a Fibonacci function with invalid arguments, restricts status values, and defines React component props.
What it assumes
Assumes familiarity with JavaScript functions and React components while introducing TypeScript annotations through an untyped function.
What you can do after
Apply it via TypeScript to annotate function parameters and React props, infer result types, and catch incompatible values.
How it connects
Connects type inference, union types, interfaces, optional properties, generics, and React component props.

Also explained in

Compare how 12 books explain static typing →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React in Depth. The section links point to the parts of the book it draws on.