Types, inference and unions

Annotate variables, let TypeScript infer the rest, and combine types with unions and literal types.

Runs in Zerethon IDE · TypeScript 7 Official TypeScript documentation ↗
main.ts
let count = 3;               // inferred as number
const userName: string = 'Ada';
let id: number | string = 42; // a union
id = 'A-42';

type Direction = 'up' | 'down'; // literal types
const move: Direction = 'up';

let maybe: string | undefined;
console.log(count + 1, userName, id, move, maybe ?? 'none');
console.log(Number('42') + 1, String(7) + 7);

Output

4 Ada A-42 up none
43 77
  • Write types where they help: function parameters, public data shapes. Let inference handle local variables.
  • Avoid any — it switches checking off. Use unknown for values you must check first.
  • Strict mode is on: null and undefined are separate types, so string | undefined must be checked before use.