Curriculum
Course: TypeScript
Login
Text lesson

TS Aliases and Interfaces

TypeScript allows types to be defined independently from the variables that use them.

Aliases and interfaces enable easy sharing of types between different variables and objects.

Type Aliases

Type aliases allow you to define types with a custom name (an alias).

Type aliases can be used for both primitive types like string and more complex types such as objects and arrays.

Example

type CarYear = number
type CarType = string
type CarModel = string
type Car = {
  year: CarYear,
  type: CarType,
  model: CarModel
}

const carYear: CarYear = 2001
const carType: CarType = “Toyota”
const carModel: CarModel = “Corolla”
const car: Car = {
  year: carYear,
  type: carType,
  model: carModel
};

Interfaces

Interfaces are similar to type aliases but are specifically used for defining object types.

Example

interface Rectangle {
  height: number,
  width: number
}

const rectangle: Rectangle = {
  height: 20,
  width: 10
};

Extending Interfaces

Interfaces can extend one another, allowing for the augmentation of their definitions.

Extending an interface means creating a new interface that includes the properties of the original interface, along with additional properties.

Example

interface Rectangle {
  height: number,
  width: number
}

interface ColoredRectangle extends Rectangle {
  color: string
}

const coloredRectangle: ColoredRectangle = {
  height: 20,
  width: 10,
  color: “red”
};