TypeScript Cheatsheet
Quick reference for TypeScript syntax — types, interfaces, generics, utility types, and more.
Primitive Types
let name: string = "Alice";
let age: number = 30;
let active: boolean = true;
let nothing: null = null;
let undef: undefined = undefined;
let anything: any = "whatever";
let val: unknown = getData(); // safer than anyArrays & Tuples
// Arrays
let nums: number[] = [1, 2, 3];
let strs: Array<string> = ["a", "b"];
// Tuples — fixed-length, typed positions
let pair: [string, number] = ["Alice", 30];
let coords: [number, number, number] = [0, 0, 0];Interfaces
interface User {
id: number;
name: string;
email?: string; // optional
readonly createdAt: Date; // read-only
}
// Extending interfaces
interface Admin extends User {
role: "admin" | "superadmin";
}
// Index signatures
interface StringMap {
[key: string]: string;
}Type Aliases
type ID = string | number;
type Status = "active" | "inactive" | "pending";
type Point = { x: number; y: number };
// Function type
type Handler = (event: MouseEvent) => void;
// Intersection types
type AdminUser = User & { role: string };Functions
// Parameter and return types
function greet(name: string): string {
return `Hello, ${name}`;
}
// Optional and default parameters
function log(msg: string, level?: string, prefix = "LOG") {}
// Rest parameters
function sum(...nums: number[]): number {
return nums.reduce((a, b) => a + b, 0);
}
// Arrow functions
const double = (n: number): number => n * 2;Generics
// Generic function
function identity<T>(val: T): T {
return val;
}
// Generic interface
interface ApiResponse<T> {
data: T;
status: number;
message: string;
}
// Generic constraints
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
// Multiple type parameters
function merge<T, U>(a: T, b: U): T & U {
return { ...a, ...b } as T & U;
}Utility Types
interface User { id: number; name: string; email: string; }
Partial<User> // all fields optional
Required<User> // all fields required
Readonly<User> // all fields read-only
Pick<User, "id" | "name"> // keep only id and name
Omit<User, "email"> // remove email
Record<string, User> // { [key: string]: User }
Exclude<"a" | "b" | "c", "a"> // "b" | "c"
Extract<"a" | "b", "a" | "d"> // "a"
NonNullable<string | null> // string
ReturnType<typeof myFn> // return type of function
Parameters<typeof myFn> // parameter types tupleEnums
// Numeric enum
enum Direction { Up, Down, Left, Right }
const dir: Direction = Direction.Up; // 0
// String enum
enum Status {
Active = "ACTIVE",
Inactive = "INACTIVE",
}
// Const enum (inlined at compile time)
const enum Size { Small = 1, Medium = 2, Large = 3 }Type Guards
// typeof
function print(val: string | number) {
if (typeof val === "string") {
console.log(val.toUpperCase());
}
}
// instanceof
function handle(err: Error | string) {
if (err instanceof Error) {
console.log(err.message);
}
}
// Custom type guard
function isUser(obj: unknown): obj is User {
return typeof obj === "object" && obj !== null && "id" in obj;
}Mapped & Conditional Types
// Mapped type
type Optional<T> = { [K in keyof T]?: T[K] };
// Conditional type
type IsString<T> = T extends string ? true : false;
// Infer
type UnpackPromise<T> = T extends Promise<infer U> ? U : T;
// Template literal types
type EventName = `on${Capitalize<string>}`;Classes
class Animal {
readonly name: string;
#sound: string; // private field (ES2022)
constructor(name: string, sound: string) {
this.name = name;
this.#sound = sound;
}
speak(): string {
return `${this.name} says ${this.#sound}`;
}
}
// Abstract class
abstract class Shape {
abstract area(): number;
describe() { return `Area: ${this.area()}`; }
}
// Implementing interfaces
class Dog extends Animal implements Serializable {
serialize() { return JSON.stringify(this); }
}Frequently Asked Questions
What is the difference between interface and type in TypeScript?
Both define object shapes. Interfaces support declaration merging and are extensible with extends. Type aliases are more flexible — they can represent unions, intersections, primitives, and mapped types. Use interface for object shapes; use type for everything else.
What are utility types in TypeScript?
Utility types are built-in generics that transform other types. Examples: Partial<T> (all fields optional), Pick<T, K> (select fields), Omit<T, K> (exclude fields), Record<K, V> (object map), ReturnType<T> (function return type).
When should I use unknown instead of any?
Use unknown when a value could be anything but you want to handle it safely. Unlike any, you must narrow the type (with typeof, instanceof, or a type guard) before using it. This prevents runtime errors that any silently allows.
How do generics work in TypeScript?
Generics are type parameters that let you write reusable code across multiple types. Declare a generic function with <T> and call it with a specific type like identity<string>('hello'). The compiler infers T from the argument when possible.
What does strict mode do in TypeScript?
strict: true in tsconfig.json enables strictNullChecks (no null/undefined without explicit union), noImplicitAny (all variables must be typed), strictFunctionTypes, and others. It catches more bugs but requires more type annotations.
From the blog
View all →
May 13, 2026
Convert XML to JSON Online: Complete Guide for Developers (2026)

May 11, 2026
Convert CSV to JSON Online Free (Best Developer Guide 2026)

May 6, 2026
Convert YAML to JSON Online Free (2026 Developer Guide)

Apr 30, 2026
Convert JSON to Zod Schema Online (2026) – Free Tool & Complete Guide

Apr 30, 2026
Top 50 JavaScript to TypeScript Converters (2026) – Free, AI & Online Tools
Have JavaScript code to convert to TypeScript?
Use the JS to TS Converter →