Published on

Understanding TypeScript Interfaces

Authors
  • avatar
    Name
    hwahyeon
    Twitter

In TypeScript, an interface defines the structure of an object. It acts as a blueprint that specifies what properties an object should have and what types those properties should be. Only objects that follow this structure are allowed.

Example 1: Basic interface

interface Fruit {
  name: string // Name of the fruit
  price: number // Price of the fruit
}

const apple: Fruit = {
  name: 'Apple',
  price: 1000,
}

const banana: Fruit = {
  name: 'Banana',
  price: 1200,
}

In this example, both apple and banana follow the Fruit interface structure.

Example 2: Optional Properties

interface Fruit {
  name: string
  price: number
  discount?: number // Optional property
}

const orange: Fruit = {
  name: 'Orange',
  price: 3,
}

const mango: Fruit = {
  name: 'Mango',
  price: 4,
  discount: 0.5, // Discount is provided in this case
}

The discount property is optional, meaning it can be omitted when creating a Fruit object.