TypeScript by Example

Basic Types

TypeScript's scalar vocabulary: string, number, boolean, null, undefined, symbol, bigint, any, and unknown.

TypeScript adds static types on top of JavaScript values. Most annotations are optional, but the basic vocabulary helps when inference needs a hint.

Primitive annotations appear after the variable name with a colon.

const username: string = "Alice";
const age: number = 30;
const active: boolean = true;
const nothing: null = null;
const missing: undefined = undefined;
const id: symbol = Symbol("id");
const big: bigint = 9007199254740993n;

any opts out of checking. unknown is safer: you must prove the type before using the value.

let loose: any = "hello";
loose = 42;
loose.toFixed(2); // no checking
 
let raw: unknown = JSON.parse('{"x": 1}');
 
if (typeof raw === "object" && raw !== null && "x" in raw) {
  const candidate = raw as { x: unknown };
  if (typeof candidate.x === "number") {
    console.log(candidate.x);
  }
}

In production

Ban new any with lint rules and use unknown at trust boundaries: JSON.parse, API responses, queues, and plugin inputs. unknown forces one local proof before the rest of the code can treat the value as safe.

Enjoyed this? Get more software craft delivered to your inbox.