Toggle theme

TypeScript Snippets

Type-safe JavaScript code snippets and patterns

Type Interfaces

typescript

Define custom types using interfaces

interface User {
  id: number;
  name: string;
  email: string;
  age?: number; // Optional property
}

const user: User = {
  id: 1,
  name: 'John',
  email: 'john@example.com'
};

Generic Functions

typescript

Create reusable generic functions

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

// Usage
const numbers = [1, 2, 3];
const firstNum = getFirstElement(numbers); // Type: number

const strings = ['a', 'b', 'c'];
const firstStr = getFirstElement(strings); // Type: string

Union Types

typescript

Combine multiple types using unions

type Status = 'pending' | 'success' | 'error';

interface ApiResponse {
  status: Status;
  data: string | null;
  error?: string;
}

function handleResponse(response: ApiResponse) {
  switch (response.status) {
    case 'success':
      console.log(response.data);
      break;
    case 'error':
      console.error(response.error);
      break;
  }
}

Type Guards

typescript

Use type guards for runtime type checking

interface Bird {
  type: 'bird';
  flySpeed: number;
}

interface Horse {
  type: 'horse';
  runSpeed: number;
}

type Animal = Bird | Horse;

function moveAnimal(animal: Animal) {
  if (animal.type === 'bird') {
    console.log(`Flying at ${animal.flySpeed}km/h`);
  } else {
    console.log(`Running at ${animal.runSpeed}km/h`);
  }
}