DEV Community

Cover image for Master Complete TypeScript Cheat Sheet.
CodeWithDhanian
CodeWithDhanian

Posted on

2

Master Complete TypeScript Cheat Sheet.

Want to master TypeScript with full projects, tips, and best practices? Grab the full ebook here:

➡️ https://codewithdhanian.gumroad.com/l/hkztg


1. Basic Types

// Primitive types
let age: number = 25;
let userName: string = "Alice";
let isAdmin: boolean = true;

// Arrays
let scores: number[] = [90, 80, 70];
let fruits: Array<string> = ["apple", "banana"];

// Tuples (fixed length and types)
let user: [string, number] = ["John", 30];

// Object
let person: { name: string; age: number } = {
  name: "Bob",
  age: 40,
};

// Null and Undefined
let nothing: null = null;
let something: undefined = undefined;

// Any (avoid if possible)
let randomValue: any = 5;
randomValue = "Hello";

// Unknown (safer than any)
let input: unknown = "Test";
// input.toUpperCase(); // Error without type check
if (typeof input === "string") {
  input.toUpperCase();
}
Enter fullscreen mode Exit fullscreen mode

2. Functions

// Function with type annotations
function add(a: number, b: number): number {
  return a + b;
}

// Optional parameters
function greet(name?: string): void {
  console.log(`Hello, ${name || "Guest"}`);
}

// Default parameters
function multiply(a: number, b: number = 2): number {
  return a * b;
}
Enter fullscreen mode Exit fullscreen mode

3. Type Aliases and Interfaces

// Type alias
type UserID = number | string;

// Interface
interface User {
  id: UserID;
  name: string;
  isAdmin: boolean;
}

// Extending interfaces
interface Admin extends User {
  role: string;
}
Enter fullscreen mode Exit fullscreen mode

4. Advanced Types

// Union types
let id: number | string = 123;

// Intersection types
type Employee = { name: string } & { age: number };

// Literal types
let direction: "left" | "right" | "center" = "left";

// Enum (constant sets)
enum Status {
  Pending,
  Active,
  Completed,
}
let taskStatus: Status = Status.Active;
Enter fullscreen mode Exit fullscreen mode

5. Classes and Access Modifiers

class Animal {
  public name: string;
  protected age: number;
  private isAlive: boolean;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
    this.isAlive = true;
  }

  public greet(): void {
    console.log(`Hi, I'm ${this.name}`);
  }
}

// Inheritance
class Dog extends Animal {
  breed: string;

  constructor(name: string, age: number, breed: string) {
    super(name, age);
    this.breed = breed;
  }

  bark(): void {
    console.log("Woof!");
  }
}
Enter fullscreen mode Exit fullscreen mode

6. Generics

// Generic function
function identity<T>(arg: T): T {
  return arg;
}

// Generic array
let output = identity<string>("Hello");

// Generic interface
interface ApiResponse<T> {
  data: T;
  status: number;
}

// Generic class
class Box<T> {
  contents: T;
  constructor(contents: T) {
    this.contents = contents;
  }
}
Enter fullscreen mode Exit fullscreen mode

7. Utility Types

// Partial (make properties optional)
type PartialUser = Partial<User>;

// Required (make all properties required)
type RequiredUser = Required<User>;

// Pick (select specific properties)
type PickUser = Pick<User, "id" | "name">;

// Omit (remove specific properties)
type OmitUser = Omit<User, "isAdmin">;

// Readonly (make properties immutable)
type ReadonlyUser = Readonly<User>;
Enter fullscreen mode Exit fullscreen mode

8. Type Guards and Narrowing

// Type guard with typeof
function padLeft(value: string, padding: string | number) {
  if (typeof padding === "number") {
    return Array(padding + 1).join(" ") + value;
  }
  if (typeof padding === "string") {
    return padding + value;
  }
  throw new Error("Expected string or number");
}

// Type guard with 'in' keyword
interface Fish { swim(): void }
interface Bird { fly(): void }

function move(animal: Fish | Bird) {
  if ("swim" in animal) {
    animal.swim();
  } else {
    animal.fly();
  }
}
Enter fullscreen mode Exit fullscreen mode

9. Mapped, Conditional, and Template Literal Types

// Mapped types
type OptionsFlags<Type> = {
  [Property in keyof Type]: boolean;
};

// Conditional types
type IsString<T> = T extends string ? true : false;

// Template literal types
type EventName = `on${Capitalize<string>}`;
Enter fullscreen mode Exit fullscreen mode

10. Modules, Namespaces, and Configurations

// Export and Import (ES Modules)
export interface Car {
  model: string;
}

import { Car } from "./Car";

// Namespace (old pattern)
namespace Utility {
  export function log(message: string) {
    console.log(message);
  }
}
Utility.log("Test");
Enter fullscreen mode Exit fullscreen mode
// tsconfig.json essentials
{
  "compilerOptions": {
    "target": "ES6",
    "module": "commonjs",
    "strict": true,
    "esModuleInterop": true,
    "outDir": "./dist",
    "rootDir": "./src"
  }
}
Enter fullscreen mode Exit fullscreen mode

11. DOM and Events

// Access DOM elements safely
const button = document.querySelector('button') as HTMLButtonElement;

button.addEventListener('click', (e: MouseEvent) => {
  console.log(e.clientX, e.clientY);
});
Enter fullscreen mode Exit fullscreen mode

12. TypeScript with React, Node.js, Express

// React Props typing
interface ButtonProps {
  text: string;
}

const Button: React.FC<ButtonProps> = ({ text }) => {
  return <button>{text}</button>;
};

// Express Request typing
import express, { Request, Response } from 'express';

const app = express();
app.get('/', (req: Request, res: Response) => {
  res.send('Hello with TypeScript');
});
Enter fullscreen mode Exit fullscreen mode

13. Advanced Topics

// Keyof and typeof
type UserKeys = keyof User; // "id" | "name" | "isAdmin"
const uName: UserKeys = "name";

// Infer (conditional inferencing)
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;

// Declaration Merging
interface Window {
  myCustomProp: string;
}

// Decorators (experimental)
function Log(target: any, propertyKey: string) {
  console.log(`${propertyKey} was accessed`);
}
class Cat {
  @Log
  name: string = "Whiskers";
}
Enter fullscreen mode Exit fullscreen mode

Final Thoughts

TypeScript is more than a language upgrade — it's a career upgrade.

It will make you a better JavaScript developer, a stronger backend engineer, and an even more reliable React or Node.js developer.

If you want to truly master it, grab the full ebook packed with full projects, in-depth explanations, and real-world examples:

➡️ Click here to get it: https://codewithdhanian.gumroad.com/l/hkztg

You owe it to your future self to master TypeScript. Start today!

Neon image

⚡ Set up a Neon project in seconds and connect from a Next.js application

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

Top comments (0)

Postmark Image

"Please fix this..."

Focus on creating stellar experiences without email headaches. Postmark's reliable API and detailed analytics make your transactional emails as polished as your product.

Start free

Join the Runner H "AI Agent Prompting" Challenge: $10,000 in Prizes for 20 Winners!

Runner H is the AI agent you can delegate all your boring and repetitive tasks to - an autonomous agent that can use any tools you give it and complete full tasks from a single prompt.

Check out the challenge

DEV is bringing live events to the community. Dismiss if you're not interested. ❤️