stackademic

The leading education platform for anyone with an interest in software development.

TypeScript Interfaces

Define object shapes, optional properties, and extendable contracts

Overview

Interfaces describe the shape of objects. They support optional and readonly properties, method signatures, and extension. Use interfaces for public APIs and object-oriented patterns; type aliases overlap for many use cases.

Syntax / Usage

interface User {
  id: string
  name: string
  email?: string
  readonly createdAt: Date
}

interface Admin extends User {
  permissions: string[]
}

function greet(user: User): string {
  return `Hello, ${user.name}`
}

// Index signature for dynamic keys
interface StringMap {
  [key: string]: string
}

// Implementing in a class
class DbUser implements User {
  id: string
  name: string
  createdAt: Date
  constructor(id: string, name: string) {
    this.id = id
    this.name = name
    this.createdAt = new Date()
  }
}

Examples

API response contract:

interface PaginatedResponse<T> {
  data: T[]
  page: number
  total: number
}

interface Post {
  id: string
  title: string
}

const res: PaginatedResponse<Post> = await fetchPosts()

Function type in an interface:

interface Logger {
  log(message: string): void
  error(message: string, code?: number): void
}

Common Mistakes

  • Declaring optional fields without handling undefined at use sites
  • Using interfaces for unions—use type instead
  • Duplicate interface merging surprises in global augmentation
  • Extending interfaces when composition (&) is clearer

See Also

basic-types generics utility-types unions