TypeScript Cheatsheet

View saved

TypeScript adds static types to JavaScript so many mistakes show up in the editor before runtime.

Start with type annotations on function boundaries, then grow into interfaces, unions, and generics as your code needs them.

Basics

Annotate a variable

Declare the type after the name. TypeScript can often infer it; annotate when clarity helps.

let count: number = 0;
const name: string = "Ada";

Common primitives

string, number, boolean, null, undefined, and bigint.

let ok: boolean = true;
let maybe: string | null = null;

Arrays

Use T[] or Array<T> for lists of one type.

const nums: number[] = [1, 2, 3];
const tags: Array<string> = ["ts", "js"];

any vs unknown

any turns checks off. Prefer unknown and narrow before use.

function handle(x: unknown) {
  if (typeof x === "string") console.log(x.toUpperCase());
}

tsc / tsconfig

Compile with tsc. tsconfig.json sets strictness and module options.

npx tsc --init
npx tsc

Objects & interfaces

interface

Name the shape of an object. Optional fields use ?.

interface User {
  id: number;
  name: string;
  email?: string;
}

type alias

Alias any type, including unions and tuples.

type Id = string | number;
type Point = [number, number];

Readonly

Prevent reassignment of properties after creation.

interface Config {
  readonly apiUrl: string;
}

Index signatures

Allow dynamic keys when the value type is known.

interface Dict {
  [key: string]: number;
}

Extending

Build on existing interfaces with extends.

interface Admin extends User {
  role: "admin";
}

Functions

Typed parameters

Annotate parameters and the return type at function boundaries.

function add(a: number, b: number): number {
  return a + b;
}

Optional / default params

Mark optional with ? or provide a default value.

function greet(name: string = "friend"): string {
  return `Hi, ${name}`;
}

Function type

Describe a callable as a type.

type Mapper = (n: number) => number;
const double: Mapper = (n) => n * 2;

void

Use void when a function returns no meaningful value.

function log(msg: string): void {
  console.log(msg);
}

Unions & narrowing

Union types

A value that can be one of several types.

type Status = "idle" | "loading" | "error";

typeof narrowing

Narrow unions with runtime checks so TypeScript knows the type inside a branch.

function len(x: string | string[]) {
  if (typeof x === "string") return x.length;
  return x.length;
}

Discriminated unions

Share a tag field so each variant is easy to distinguish.

type Result =
  | { ok: true; value: string }
  | { ok: false; error: string };

as assertion

Tell the compiler you know the type—use sparingly when you cannot narrow.

const el = document.querySelector("#app") as HTMLElement;

Generics & tips

Generic function

Parameterize a type so one function works for many shapes.

function first<T>(items: T[]): T | undefined {
  return items[0];
}

Partial / Pick

Utility types transform existing object types.

type UserUpdate = Partial<User>;
type UserName = Pick<User, "name">;

strict mode

Enable strict in tsconfig.json for stronger checks.

{
  "compilerOptions": { "strict": true }
}

Import types

Import only a type when no runtime value is needed.

import type { User } from "./user";

Comments

One comment per signed-in account. Comments are saved with this page’s URL.