← React / TypeScript

React / TypeScript · 08 / 18

TypeScript types and modules

Describe allowed data shapes and check them before execution.

  • Small
  • Basics
  • 15 min

Prerequisites: HTML and CSS: the foundation of a web interface

TypeScript adds type descriptions to JavaScript. The compiler checks them before producing JavaScript. A type does not automatically validate unknown network data. In House Log, TypeScript describes the shape of a record. Other modules can import that description.

Example files

01Describe a shape

type Entry defines the id, title and costCents properties. ? makes costCents optional. The function accepts values matching this shape. Numbers and text have different types.

types.ts · typescriptOpen file
export type Entry = { id: string; title: string; costCents?: number };
export function describe(entry: Entry): string {
  return `${entry.title}: ${(entry.costCents ?? 0) / 100} EUR`;
}
console.log(describe({ id: 'e1', title: 'Roof', costCents: 12990 }));

Run / check

npx tsc types.ts --strict --target ES2022 --module NodeNext
node types.js

02Compile and run

Install TypeScript in the learning folder with npm install --save-dev typescript@6.0.3. Run npx tsc types.ts --strict --target ES2022 --module NodeNext, then node types.js. The compiler creates an additional JavaScript file.

03Understand modules and boundaries

export makes a name available to other files. import type uses the type there. No runtime representation of this type description remains. External data therefore requires additional validation. Later we use a parser for that.

Expected result

Roof: 129.9 EUR

Your exercise

Replace costCents: 12990 with costCents: "12990" and run only the compiler.

Show the solution and explanation

The compiler reports that string cannot be assigned to number. Convert confirmed form inputs explicitly. An as Entry after JSON.parse would instead be an assertion rather than validation.

Project context and sources

The example is simplified for learning. The linked source version shows its use in the project and the checks applied there.