๐ŸŽ“ A1Learner
๐Ÿ”

TypeScript Type Aliases

A type alias gives a name to a type. One alias can name a union, an object shape, or a tuple.

Name a union

The ID alias names a union of string and number. Both kinds of value fit the alias.

type ID = string | number;

const first: ID = "A-101";
const second: ID = 42;
console.log(first);
console.log(second);

Name an object shape

The Point alias names an object shape. The variable logs each field.

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

const point: Point = { x: 3, y: 4 };
console.log(point.x);
console.log(point.y);

Name a tuple

The Pair alias names a tuple type. The variable logs each value by index.

type Pair = [string, number];

const pair: Pair = ["Ada", 36];
console.log(pair[0]);
console.log(pair[1]);

Example

type ID = string | number;

type Product = {
  id: ID;
  title: string;
  price: number;
};

const book: Product = { id: "B-7", title: "Dune", price: 15 };
const game: Product = { id: 9, title: "Chess", price: 20 };
console.log(book.id);
console.log(book.title);
console.log(game.id);
console.log(game.title);

Key points

  • The type keyword starts an alias.
  • An alias can name any type.
  • An interface names an object shape.
  • An interface can be extended by another interface.
  • Two declarations of one interface merge into a single shape.
  • An alias name and the type it names can be used in place of each other.

In this example, the ID alias names a union type. The Product alias names an object shape that uses ID for its id field. The book uses a string id and the game uses a number id. Both values fit the same Product type.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท TypeScript Playground

Exercise

Which types can a type alias name?