sajad torkamani

Types and interfaces can be used interchangeably in most scenarios but there are a few key differences.

1. An interface can be augmented but a type cannot be

interface Person {
  name: string
  age: number
}

interface Person {
  gender: string
}

const jim: Person = {
  name: 'Jim',
  age: 30,
  gender: 'Male'
}

This code runs fine. The second declaration of the Person interface “augments” any previous Person interface so that the Person interface includes the name, age, and gender properties.

Doing the same using a type will cause an error:

1. An interface can be augment but a type cannot be

Types support mapped types

A type lets you use mapped types:

type FeatureConfig = {  
  darkMode: () => void;
  betaDashboard: () => void;
}

type ConfigFlags<Type> = {
  [Property in keyof Type]: boolean
}

type FeatureFlags = ConfigFlags<FeatureConfig>
// FeatureFlags is now equal to { darkMode: number; betaDashboard: number }

You can’t do that with an interface.

Tagged: TypeScript

Leave a comment

Your email address will not be published. Required fields are marked *