02 basic types

JavaScript has dynamic types TypeScript adds a static layer on top and erases it at build time Learn the primitives first, the rest is composition

Table of Contents

Primitives

const inferred = "hello";
let count: number = 1;
const enabled: boolean = true;
const nothing: null = null;
const missing: undefined = undefined;
const big: bigint = 10n;
const key: symbol = Symbol("key");

string , number , boolean , null , undefined , bigint , symbol No surprises , these map to JavaScript values

Inference

let msg = "hello there";
// inferred as string

Do not annotate what the compiler already knows Adding : string there buys nothing and creates noise

Arrays and tuples

const ports: number[] = [22, 80, 443];
const pair: [string, number] = ["0x1RIS", 443];

number[] is homogeneous A tuple fixes length and position Use tuples for real pairs , not for lists that happen to have two items

Unions and literals

type Direction = "north" | "south";
type Port = 443 | 80;
let value: string | number = 443;

A union says the value can be one of several types A literal union narrows that further to exact values That is what makes discriminated unions work later

Interfaces

interface Target {
  host: string;
  port?: number;
}

Optional ? means the property may be absent Under strict mode you must handle that absence before using it

any and unknown

let anything: any = 1;
let unknownValue: unknown = "maybe";

any turns off checking unknown is the safe counterpart , you must narrow it before use

if (typeof unknownValue === "string") {
  console.log(unknownValue.toUpperCase());
}

I use unknown for data crossing a trust boundary: HTTP bodies, files, CLI input any is a debt you pay later

Posted