Interfaces and Types

1/2/2025

Interfaces and Types

TypeScript provides powerful ways to define the shape of objects through interfaces and type aliases.

Interfaces

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

const user: User = {
  id: 1,
  name: 'John',
  email: '[email protected]'
}

Type Aliases

typescript
type Point = {
  x: number
  y: number
}

type ID = string | number

Extending Interfaces

typescript
interface Animal {
  name: string
}

interface Dog extends Animal {
  breed: string
}

const myDog: Dog = {
  name: 'Buddy',
  breed: 'Golden Retriever'
}

Union Types

typescript
function printId(id: string | number) {
  if (typeof id === 'string') {
    console.log(id.toUpperCase())
  } else {
    console.log(id)
  }
}

Intersection Types

typescript
type Employee = {
  employeeId: number
  department: string
}

type Manager = User & Employee