TypeScript's type system lets us describe data more clearly. Common categories include primitive types, arrays, tuples, enums, union types, and literal types.
Primitive Types
let title: string = "TypeScript";
let count: number = 10;
let enabled: boolean = true;
let big: bigint = 9007199254740991n;string represents text, number represents both integers and floating-point numbers, and boolean represents true or false values.
Arrays
Arrays can be declared in two common ways.
let numbers: number[] = [1, 2, 3];
let names: Array<string> = ["Alice", "Bob"];When elements should share a type, make that element type explicit.
Tuples
Tuples describe fixed-position data.
let user: [string, number] = ["Alice", 25];
let option: [string, boolean?] = ["dark"];
let list: [number, ...string[]] = [1, "a", "b"];Enums
Enums define named constants.
enum Color {
Red,
Green,
Blue,
}
const favorite: Color = Color.Green;In many projects, union literals are also a practical alternative.
type Direction = "up" | "down" | "left" | "right";Union Types
Union types allow a value to be one of several types.
let id: string | number;
id = "u_1";
id = 1001;They are useful for API parameters, form inputs, and state values.
Literal Types
Literal types restrict values to exact options.
type Gender = "male" | "female";
type Status = "idle" | "loading" | "success" | "error";This makes state modeling safer and avoids many magic-string mistakes.