← All Tools

🔷 TypeScript Cheat Sheet

87+ code examples • Click sections to expand/collapse • Search anything

Basic Types 12Interfaces & Types 9Functions 8Generics 8Utility Types 12Classes 6Enums & Const 4Type Guards & Narrowing 6Mapped & Conditional Types 6Async & Promises 5Module Patterns 7Config & Decorators 4

Basic Types 12

String type
let name: string = "Alice";
Number type
let age: number = 30;
Boolean type
let active: boolean = true;
Array of strings
let items: string[] = ["a", "b"];
Tuple type
let tuple: [string, number] = ["a", 1];
Union type
let id: string | number = "abc";
Any type (escape hatch)
let anything: any = 42;
Unknown type (safer than any)
let unknown: unknown = getData();
Void type
let nothing: void = undefined;
Never type
let nope: never = (() => { throw Error(); })();
Symbol type
let sym: symbol = Symbol("id");
BigInt type
let big: bigint = 100n;

Interfaces & Types 9

Interface with optional property
interface User {
  name: string;
  age: number;
  email?: string;  // optional
}
Readonly property
interface ReadonlyUser {
  readonly id: number;
  name: string;
}
Index signature
interface StringMap {
  [key: string]: string;
}
Type alias for object
type Point = { x: number; y: number };
Type alias for union
type ID = string | number;
String literal union
type Status = "active" | "inactive" | "banned";
Interface inheritance
interface Animal { name: string; }
interface Dog extends Animal { breed: string; }
Intersection type
type Admin = User & { role: string };
Interface with method
interface Clickable {
  onClick(event: MouseEvent): void;
}

Functions 8

Typed function
function greet(name: string): string {
  return `Hello ${name}`;
}
Arrow function with types
const add = (a: number, b: number): number => a + b;
Optional parameter
function log(msg: string, level?: string): void {}
Default parameter
function create(name: string, age: number = 25) {}
Rest parameters
function sum(...nums: number[]): number {
  return nums.reduce((a, b) => a + b, 0);
}
Function overloads
function parse(input: string): number;
function parse(input: number): string;
function parse(input: any): any { /*...*/ }
Function type alias
type Callback = (data: string) => void;
Inline function type
const fn: (x: number) => boolean = x => x > 0;

Generics 8

Generic function
function identity<T>(arg: T): T { return arg; }
Generic arrow function
const identity = <T>(arg: T): T => arg;
Generic interface
interface Box<T> { value: T; }
Generic class
class Container<T> {
  constructor(public value: T) {}
}
Generic constraint
function getLength<T extends { length: number }>(arg: T): number {
  return arg.length;
}
Multiple type parameters
function merge<T, U>(a: T, b: U): T & U {
  return { ...a, ...b };
}
keyof constraint
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}
Generic type alias
type Nullable<T> = T | null;

Utility Types 12

All properties optional
Partial<User>
All properties required
Required<User>
All properties readonly
Readonly<User>
Pick specific properties
Pick<User, 'name' | 'email'>
Omit specific properties
Omit<User, 'password'>
Object with typed keys/values
Record<string, number>
Exclude from union → 'b' | 'c'
Exclude<'a' | 'b' | 'c', 'a'>
Extract from union → 'a' | 'b'
Extract<'a' | 'b' | 'c', 'a' | 'b'>
Remove null/undefined → string
NonNullable<string | null | undefined>
Get function return type
ReturnType<typeof myFunc>
Get function parameter types as tuple
Parameters<typeof myFunc>
Unwrap Promise type → string
Awaited<Promise<string>>

Classes 6

Parameter properties (shorthand)
class Animal {
  constructor(
    public name: string,
    private age: number,
    protected sound: string
  ) {}
}
Inheritance
class Dog extends Animal {
  constructor(name: string, public breed: string) {
    super(name, 0, 'woof');
  }
}
Abstract class
abstract class Shape {
  abstract area(): number;
  describe() { return `Area: ${this.area()}`; }
}
Singleton pattern
class Singleton {
  private static instance: Singleton;
  private constructor() {}
  static getInstance() {
    return this.instance ??= new Singleton();
  }
}
Implementing interface
class Logger implements ILogger {
  log(msg: string) { console.log(msg); }
}
Private fields (ES vs TS)
class Config {
  #secret = 'hidden';  // ES private
  private key = 'also private';  // TS private
}

Enums & Const 4

Numeric enum
enum Direction {
  Up,     // 0
  Down,   // 1
  Left,   // 2
  Right   // 3
}
String enum
enum Color {
  Red = '#ff0000',
  Green = '#00ff00',
  Blue = '#0000ff'
}
Const enum (inlined at compile)
const enum Status {
  Active = 1,
  Inactive = 0
}
as const alternative to enum
const Direction = {
  Up: 'UP',
  Down: 'DOWN'
} as const;
type Direction = typeof Direction[keyof typeof Direction];

Type Guards & Narrowing 6

typeof guard
if (typeof x === 'string') {
  x.toUpperCase(); // x is string
}
instanceof guard
if (x instanceof Date) {
  x.getTime(); // x is Date
}
in operator guard
if ('name' in obj) {
  obj.name; // narrowed
}
Custom type guard
function isString(x: unknown): x is string {
  return typeof x === 'string';
}
Assertion function
function assertDefined<T>(val: T): asserts val is NonNullable<T> {
  if (val == null) throw Error('Undefined!');
}
Discriminated union
type Shape = Circle | Square;
switch (shape.kind) {
  case 'circle': /* Circle */ break;
  case 'square': /* Square */ break;
}

Mapped & Conditional Types 6

Mapped type (make optional)
type Optional<T> = {
  [K in keyof T]?: T[K];
};
Mapped type (make readonly)
type Immutable<T> = {
  readonly [K in keyof T]: T[K];
};
Key remapping
type Getters<T> = {
  [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
Conditional type
type IsString<T> = T extends string ? true : false;
infer keyword
type Flatten<T> = T extends Array<infer U> ? U : T;
Recursive conditional type
type DeepReadonly<T> = {
  readonly [K in keyof T]: T[K] extends object
    ? DeepReadonly<T[K]>
    : T[K];
};

Async & Promises 5

Async function with return type
async function fetchUser(id: number): Promise<User> {
  const res = await fetch(`/api/users/${id}`);
  return res.json();
}
Generic async function
const fetchAll = async <T>(urls: string[]): Promise<T[]> => {
  return Promise.all(urls.map(u => fetch(u).then(r => r.json())));
};
Async function type
type AsyncFn<T> = () => Promise<T>;
API response type pattern
interface ApiResponse<T> {
  data: T;
  error?: string;
  status: number;
}
Safe fetch with error handling
async function safeFetch<T>(url: string): Promise<T | null> {
  try {
    const res = await fetch(url);
    if (!res.ok) return null;
    return res.json();
  } catch { return null; }
}

Module Patterns 7

Named export
export interface Config { port: number; }
Default export
export default class App {}
Type-only export
export type { User };  // type-only export
Type-only import
import type { Config } from './config';
Inline type import
import { type User, createUser } from './user';
Module declaration (CSS modules)
declare module '*.css' {
  const styles: Record<string, string>;
  export default styles;
}
Global augmentation
declare global {
  interface Window { analytics: Analytics; }
}

Config & Decorators 4

Recommended tsconfig
// tsconfig.json essentials
{
  "strict": true,
  "target": "ES2022",
  "module": "ESNext",
  "moduleResolution": "bundler"
}
Decorator config
// Enable decorators
{
  "experimentalDecorators": true,
  "emitDecoratorMetadata": true
}
Method decorator
function Log(target: any, key: string, desc: PropertyDescriptor) {
  const orig = desc.value;
  desc.value = function(...args: any[]) {
    console.log(`${key} called`);
    return orig.apply(this, args);
  };
}
Path aliases
// Path aliases in tsconfig
{
  "paths": {
    "@/*": ["./src/*"],
    "@utils/*": ["./src/utils/*"]
  }
}

Made with ♥ by Kas Developer Tools

\xF0\x9F\x92\x99 Tip\xF0\x9F\x93\x9A Get Bundle \x244.99