TypeScript Cheat Sheet
Complete reference guide for TypeScript with interactive examples and live playground links
Basic Types
Type Annotations
Basic type annotations and type system features
TypeScript
// Basic types
let name: string = 'TypeScript';
let age: number = 25;
let isActive: boolean = true;
let numbers: number[] = [1, 2, 3];
let tuple: [string, number] = ['age', 25];
// Union types
let id: string | number = 'abc123';
let status: 'active' | 'inactive' = 'active';
// Type inference
let inferred = 'TypeScript'; // string
let numbers = [1, 2, 3]; // number[]
// Type assertions
let value: any = 'Hello';
let length: number = (value as string).length;
let length2: number = (<string>value).length;
Interfaces
Working with interfaces and type definitions
TypeScript
// Basic interface
interface User {
name: string;
age: number;
email?: string; // Optional property
readonly id: number; // Read-only property
}
// Interface implementation
class Person implements User {
readonly id: number;
name: string;
age: number;
constructor(id: number, name: string, age: number) {
this.id = id;
this.name = name;
this.age = age;
}
}
// Interface extension
interface Employee extends User {
department: string;
salary: number;
}
// Index signatures
interface StringMap {
[key: string]: string;
}
Type Aliases
Creating and using type aliases
TypeScript
// Basic type alias
type Point = {
x: number;
y: number;
};
// Union types
type Status = 'pending' | 'approved' | 'rejected';
// Function types
type Calculator = (x: number, y: number) => number;
// Generic types
type Container<T> = {
value: T;
getValue(): T;
};
// Mapped types
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
Enums
Working with enums
TypeScript
// Numeric enum
enum Direction {
Up = 1,
Down,
Left,
Right
}
// String enum
enum Status {
Active = 'ACTIVE',
Inactive = 'INACTIVE',
Pending = 'PENDING'
}
// Const enum
const enum Colors {
Red,
Green,
Blue
}
// Using enums
let direction: Direction = Direction.Up;
let status: Status = Status.Active;
let color: Colors = Colors.Red;
Advanced Types
Generics
Working with generic types
TypeScript
// Generic function
function identity<T>(arg: T): T {
return arg;
}
// Generic interface
interface GenericIdentityFn<T> {
(arg: T): T;
}
// Generic class
class Container<T> {
private value: T;
constructor(value: T) {
this.value = value;
}
getValue(): T {
return this.value;
}
}
// Generic constraints
interface Lengthwise {
length: number;
}
function loggingIdentity<T extends Lengthwise>(arg: T): T {
console.log(arg.length);
return arg;
}
Utility Types
Built-in utility types
TypeScript
// Partial
interface Todo {
title: string;
description: string;
}
type PartialTodo = Partial<Todo>;
// Required
type RequiredTodo = Required<Todo>;
// Readonly
type ReadonlyTodo = Readonly<Todo>;
// Pick
type TodoPreview = Pick<Todo, 'title'>;
// Omit
type TodoInfo = Omit<Todo, 'description'>;
// Record
type CatInfo = {
age: number;
breed: string;
};
type CatName = 'miffy' | 'boris';
const cats: Record<CatName, CatInfo> = {
miffy: { age: 10, breed: 'Persian' },
boris: { age: 5, breed: 'Maine Coon' }
};
Type Guards
Type narrowing and type guards
TypeScript
// Type predicates
function isString(value: any): value is string {
return typeof value === 'string';
}
// instanceof
if (pet instanceof Fish) {
pet.swim();
}
// in operator
if ('swim' in pet) {
pet.swim();
}
// typeof
if (typeof value === 'string') {
value.toUpperCase();
}
// Custom type guard
interface Bird {
fly(): void;
layEggs(): void;
}
interface Fish {
swim(): void;
layEggs(): void;
}
function isFish(pet: Fish | Bird): pet is Fish {
return (pet as Fish).swim !== undefined;
}
Functions
Function Types
Function type definitions and overloads
TypeScript
// Function type expression
type GreetFunction = (name: string) => string;
// Call signatures
interface DescribableFunction {
description: string;
(someArg: number): boolean;
}
// Construct signatures
interface ClockConstructor {
new (hour: number, minute: number): ClockInterface;
}
// Function overloads
function reverse(x: string): string;
function reverse(x: number): number;
function reverse(x: string | number): string | number {
if (typeof x === 'string') {
return x.split('').reverse().join('');
}
return -x;
}
Parameters
Function parameter types and patterns
TypeScript
// Optional parameters
function greet(name: string, greeting?: string) {
return greeting ? `${greeting}, ${name}!` : `Hello, ${name}!`;
}
// Default parameters
function createUser(name: string, role: string = 'user') {
return { name, role };
}
// Rest parameters
function sum(...numbers: number[]): number {
return numbers.reduce((total, n) => total + n, 0);
}
// Parameter destructuring
function printUser({ name, age }: { name: string; age: number }) {
console.log(`${name} is ${age} years old`);
}
Classes
Class Basics
Class definitions and inheritance
TypeScript
// Basic class
class Animal {
private name: string;
protected age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
public makeSound(): void {
console.log('Some sound');
}
}
// Inheritance
class Dog extends Animal {
private breed: string;
constructor(name: string, age: number, breed: string) {
super(name, age);
this.breed = breed;
}
public makeSound(): void {
console.log('Woof!');
}
}
// Abstract class
abstract class Vehicle {
abstract start(): void;
abstract stop(): void;
}
Access Modifiers
Class access modifiers
TypeScript
class Example {
// Public (default)
public publicField: string;
// Private
private privateField: string;
// Protected
protected protectedField: string;
// Readonly
readonly readonlyField: string;
constructor(
publicField: string,
privateField: string,
protectedField: string,
readonlyField: string
) {
this.publicField = publicField;
this.privateField = privateField;
this.protectedField = protectedField;
this.readonlyField = readonlyField;
}
}
Static Members
Static class members
TypeScript
class MathOperations {
// Static property
static PI: number = 3.14159;
// Static method
static square(x: number): number {
return x * x;
}
// Static block
static {
console.log('Class initialized');
}
}
// Using static members
console.log(MathOperations.PI);
console.log(MathOperations.square(5));
Modules
Module Syntax
Module exports and imports
TypeScript
// Exporting
export interface User {
name: string;
age: number;
}
export class UserService {
getUser(): User {
return { name: 'John', age: 30 };
}
}
// Default export
export default class Database {
connect() {
console.log('Connected to database');
}
}
// Re-exporting
export { UserService } from './user-service';
export * from './types';
Import Syntax
Module import patterns
TypeScript
// Named imports
import { User, UserService } from './user';
// Default import
import Database from './database';
// Namespace import
import * as Utils from './utils';
// Type-only imports
import type { User } from './user';
// Dynamic imports
async function loadModule() {
const module = await import('./module');
module.doSomething();
}
Module Augmentation
Extending and augmenting modules
TypeScript
// Augmenting existing module
declare module './user' {
interface User {
email: string;
}
}
// Merging declarations
interface User {
name: string;
}
interface User {
age: number;
}
// Resulting interface:
// interface User {
// name: string;
// age: number;
// }
TypeScript - Interactive Developer Reference
Hover over code blocks to copy or run in live playground