TypeScript Types Cheatsheet
typescriptTypeScript type system reference — primitives to advanced.
Primitive Types
let name: stringRepresents textual data
let greeting: string = "Hello";let count: numberRepresents numeric values including integers and floats
let age: number = 25;
let price: number = 99.99;let flag: booleanRepresents true or false values
let isActive: boolean = true;let empty: nullRepresents intentional absence of value
let data: null = null;let notDefined: undefinedRepresents uninitialized variable
let x: undefined = undefined;let sym: symbolRepresents unique immutable identifier
let id: symbol = Symbol("id");let big: bigintRepresents arbitrary precision integers
let huge: bigint = 9007199254740991n;let anything: anyDisables type checking for the variable
let flexible: any = "string";
flexible = 42;let uncertain: unknownType-safe alternative to any requiring type narrowing
let val: unknown = getInput();
if (typeof val === "string") { val.toUpperCase(); }function log(): voidRepresents absence of return value
function logMsg(msg: string): void {
console.log(msg);
}function fail(): neverRepresents values that never occur
function throwError(msg: string): never {
throw new Error(msg);
}Literal and Compound Types
type Direction = "left" | "right"Restricts value to specific string literals
type Status = "pending" | "success" | "error";
let s: Status = "pending";type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6Restricts value to specific numbers
type Port = 80 | 443 | 8080;
let port: Port = 443;type True = trueRestricts value to specific boolean
type AlwaysTrue = true;
let flag: AlwaysTrue = true;type A = TypeA | TypeBValue can be one of several types
type StringOrNumber = string | number;
let id: StringOrNumber = "abc";type C = TypeA & TypeBCombines multiple types into one
type Named = { name: string };
type Aged = { age: number };
type Person = Named & Aged;[Type1, Type2, ...]Fixed-length array with specific types per position
let coord: [number, number] = [10, 20];
let entry: [string, number] = ["age", 25];[name: Type, age: Type]Tuple with labeled elements for documentation
type Point = [x: number, y: number];
let p: Point = [5, 10];[Type1, Type2?]Tuple with optional trailing elements
type Flex = [string, number?];
let a: Flex = ["hi"];
let b: Flex = ["hi", 5];[Type1, ...Type2[]]Tuple with rest elements
type StringAndNums = [string, ...number[]];
let data: StringAndNums = ["sum", 1, 2, 3];Enums
enum Name { A, B, C }Auto-incrementing numeric values starting from 0
enum Direction { Up, Down, Left, Right }
let dir: Direction = Direction.Up; // 0enum Name { A = 1, B, C }Numeric enum with custom starting value
enum Status { Pending = 1, Active, Done }
// Active = 2, Done = 3enum Name { A = "a", B = "b" }Enum with string values requiring explicit initialization
enum Color { Red = "RED", Blue = "BLUE" }
let c: Color = Color.Red;const enum Name { A, B }Inlined at compile time for performance
const enum Size { S, M, L }
let size = Size.M; // compiles to: let size = 1;enum Name { A = 0, B = "b" }Enum mixing numeric and string values
enum Mixed { No = 0, Yes = "YES" }Interfaces and Type Aliases
interface Name { prop: Type }Defines object shape with named contract
interface User {
name: string;
age: number;
}type Name = { prop: Type }Creates named alias for any type
type Point = { x: number; y: number };
type ID = string | number;interface B extends A { }Extends existing interface with new properties
interface Animal { name: string }
interface Dog extends Animal { breed: string }type C = A & BCombines types similar to interface extension
type Animal = { name: string };
type Dog = Animal & { breed: string };interface A { } interface A { }Interfaces with same name merge automatically
interface Box { height: number }
interface Box { width: number }
// Box has both properties{ prop?: Type }Property that may be undefined
interface Config {
debug?: boolean;
timeout?: number;
}{ readonly prop: Type }Property that cannot be reassigned
interface Point {
readonly x: number;
readonly y: number;
}{ [key: string]: Type }Allows dynamic property names with consistent type
interface StringMap {
[key: string]: string;
}
let map: StringMap = { a: "hello" };{ [index: number]: Type }Array-like index access
interface StringArray {
[index: number]: string;
}
let arr: StringArray = ["a", "b"];Function Types
(param: Type) => ReturnTypeDefines function signature inline
type Greet = (name: string) => string;
const greet: Greet = (n) => `Hello ${n}`;{ (param: Type): ReturnType }Function type in object notation
interface SearchFunc {
(source: string, sub: string): boolean;
}function f(a: T, b?: U)Parameter that can be omitted
function greet(name: string, title?: string) {
return title ? `${title} ${name}` : name;
}function f(a: T = defaultValue)Parameter with default value
function createUser(name: string, role = "guest") {
return { name, role };
}function f(...args: Type[])Collects remaining arguments into array
function sum(...nums: number[]): number {
return nums.reduce((a, b) => a + b, 0);
}function f(a: A): X;
function f(a: B): Y;Multiple function signatures for different inputs
function parse(input: string): number;
function parse(input: number): string;
function parse(input: any) {
return typeof input === "string" ? parseInt(input) : String(input);
}interface I { method(param: T): R }Method declaration in interface
interface Calculator {
add(a: number, b: number): number;
subtract(a: number, b: number): number;
}{ new (param: T): Instance }Describes constructor function
interface DateConstructor {
new (value: number): Date;
}function f(this: Type, ...)Explicitly types the this context
function onClick(this: HTMLElement, e: Event) {
this.classList.toggle("active");
}Type Assertions and Const
value as TypeAsserts value is specific type
const input = document.getElementById("name") as HTMLInputElement;
input.value = "test";<Type>valueAlternative assertion syntax not usable in JSX
const canvas = <HTMLCanvasElement>document.getElementById("c");value!Asserts value is not null or undefined
function process(val: string | null) {
console.log(val!.toUpperCase());
}value as constMakes literal types readonly and narrowed
const colors = ["red", "green"] as const;
// type: readonly ["red", "green"]{ prop: value } as constMakes all object properties readonly literals
const config = { api: "/v1", timeout: 3000 } as const;
// config.timeout is 3000, not numbervalue satisfies TypeValidates type while preserving inferred type
const palette = {
red: [255, 0, 0],
green: "#00ff00"
} satisfies Record<string, string | number[]>;value as const satisfies TypeCombines const narrowing with type validation
const routes = {
home: "/",
about: "/about"
} as const satisfies Record<string, string>;Type Guards
typeof x === "type"Narrows type based on JavaScript typeof
function print(val: string | number) {
if (typeof val === "string") val.toUpperCase();
else val.toFixed(2);
}x instanceof ClassNarrows type based on constructor prototype
function handle(e: Error | Response) {
if (e instanceof Error) console.log(e.message);
else console.log(e.status);
}"prop" in objectNarrows based on property existence
type Fish = { swim: () => void };
type Bird = { fly: () => void };
function move(a: Fish | Bird) {
if ("swim" in a) a.swim(); else a.fly();
}function isX(a: any): a is XCustom guard function returning type predicate
function isString(val: unknown): val is string {
return typeof val === "string";
}function assert(x): asserts x is TThrows if condition fails otherwise narrows type
function assertDefined<T>(val: T): asserts val is NonNullable<T> {
if (val == null) throw new Error("Value is null");
}type U = { kind: "a" } | { kind: "b" }Union with common literal property for narrowing
type Shape = { kind: "circle"; r: number } | { kind: "rect"; w: number; h: number };
function area(s: Shape) {
return s.kind === "circle" ? Math.PI * s.r ** 2 : s.w * s.h;
}if (x) { ... }Narrows out null undefined empty string zero
function print(s: string | null) {
if (s) console.log(s.toUpperCase());
}if (x === y) { ... }Narrows both operands to common type
function compare(a: string | number, b: string | boolean) {
if (a === b) console.log(a.toUpperCase()); // both string
}Array.isArray(x)Narrows to array type
function process(val: string | string[]) {
if (Array.isArray(val)) val.forEach(console.log);
else console.log(val);
}