TSTypeScript

TypeScript cheatsheet – syntax overview

81 key commands and patterns for quick reference.

Basic types Arrays & tuples Functions Objects & interfaces Union, literal & narrowing Generics Utility types Classes Type operators Null safety & assertions tsc & tooling

Basic types

let a: string = "x"; let b: number = 1; let c: boolean = true;Annotate primitive types
let x = 5;Type inference: x is number
let v: unknown; let a: any;unknown (needs checking) vs. any (no checking)
let n: null = null; let u: undefined;null and undefined as types of their own
function f(): void {}No return value
function f(): never { throw new Error("x"); }Never returns
let big: bigint = 10n; let s: symbol = Symbol();More primitive types

Arrays & tuples

let l: number[] = [1, 2]; let m: Array<string> = [];Typing arrays
let t: [string, number] = ["a", 1];Tuple: fixed length and types
let t: [x: number, y: number];Named tuple
const l: readonly number[] = [1, 2];Read-only array
const k = [1, 2] as const;Tuple with literal types (readonly [1, 2])
let matrix: number[][] = [[1, 2], [3, 4]];Nested arrays

Functions

function f(a: number, b = 2): number { return a + b; }Parameter and return type, default value
function f(a: number, b?: string) {}Optional parameter
function f(...zahlen: number[]) {}Rest parameter
const f = (x: number): string => String(x);Typing an arrow function
type Cb = (wert: string) => void;Function type
function f(x: string): number; function f(x: number): string; function f(x: any): any { return x; }Overloads
function f(this: Konto) {}Specify the type of this

Objects & interfaces

interface A { id: number; name?: string }Interface with an optional field
interface B extends A { rolle: string }Extend an interface
type C = { readonly id: number }Type alias with readonly
type D = A & { extra: boolean }Intersection: combine types
{ [schluessel: string]: number }Index signature
Record<string, number>Dictionary with key and value type
obj.a?.b obj.f?.() obj.a ?? "std"Optional chaining and nullish coalescing
const { a, b }: A = obj;Destructuring with a type

Union, literal & narrowing

let id: string | number;Union type
type Richtung = "up" | "down";Literal union
typeof x === "string"Narrowing with typeof
x instanceof DateNarrowing with instanceof
"miau" in tierNarrowing with in
function ist(x: unknown): x is string { ... }Type predicate (custom type guard)
type F = { art: "a"; x: number } | { art: "b"; y: string }Discriminated union
const _: never = wert;Exhaustiveness check in the default branch

Generics

function f<T>(x: T): T { return x; }Generic function
function f<T extends { id: number }>(x: T) {}Constraint with extends
function f<T, K extends keyof T>(o: T, k: K): T[K]Type-safe property access
interface Box<T = string> { inhalt: T }Generic interface with a default
class Stapel<T> { items: T[] = []; }Generic class
erstes<number>([1, 2])Specify the type argument explicitly
const kopie = <T,>(x: T) => x;Generic arrow function (with a comma in .tsx)

Utility types

Partial<T> Required<T> Readonly<T>Fields optional / required / read-only
Pick<T, "a" | "b"> Omit<T, "id">Select / remove fields
Record<"a" | "b", number>Object with fixed keys
Exclude<A | B, A> Extract<A | B, A>Remove / keep union members
NonNullable<T>Remove null and undefined
ReturnType<typeof f> Parameters<typeof f>Return and parameter types of a function
Awaited<Promise<string>>Value of a promise (string)
InstanceType<typeof Klasse>Type of a class instance

Classes

class A { private x = 1; protected y = 2; public z = 3; }Access modifiers
class A { readonly id: number; #geheim = 1; }readonly and a truly private field (#)
constructor(private name: string) {}Parameter property: create and set the field
abstract class A { abstract f(): void; }Abstract class and method
class B implements Vertrag {}Implement an interface
override f(): void {}Safeguard overriding
static zaehler = 0; get wert() { return 1; }Static members and getters

Type operators

keyof TKeys of a type as a union
typeof wertType of a value (in type position)
T["feld"] T[number]Indexed access to field or element type
type M<T> = { [K in keyof T]?: T[K] }Mapped type
T extends string ? "ja" : "nein"Conditional type
T extends (infer U)[] ? U : neverinfer: pull out the inner type
`on${Capitalize<E>}`Template literal type
const x = {...} satisfies Typ;Check without losing the more precise type

Null safety & assertions

wert as stringType assertion (no runtime check)
el!.valueNon-null assertion (careful!)
<T>wertOld cast syntax (not in .tsx)
catch (e) { if (e instanceof Error) {} }Narrow the error in catch (unknown)
function f(x: unknown): asserts x is string {}Assertion function
liste[i] ?? standardWith noUncheckedIndexedAccess: handle T | undefined
Object.entries(obj) as [keyof T, T[keyof T]][]Typed entries (deliberately cast)

tsc & tooling

npx tsc --initCreate tsconfig.json
npx tscCompile the project (according to tsconfig)
npx tsc --noEmitOnly check types
npx tsc --watchRe-check automatically on changes
npx tsx datei.tsRun TypeScript directly
npm i -D @types/nodeInstall types for Node.js APIs
import type { A } from "./a.js";Type-only import (disappears in the JS)
// @ts-expect-error falscherAufruf();Suppress an error deliberately (reports if there is no error anymore)