Type aliases

Type aliases are used to give a new name to an existing type. Type aliases can name primitives, unions, functions, object literals, tuples, and any other types that you’d otherwise have to write by hand. It's important to reinforce the point that aliasing doesn’t actually create a new type. Rather, it creates a name that references an already-existing type.

Let's pick up our previous example from objects section:

const openingBand: {
  name: string,
  yearFormed: number,
} = {
  name: 'Minutemen',
  yearFormed: 1980,
};

const headliningBand: {
  name: string,
  yearFormed: number,
} = {
  name: 'Black Flag',
  yearFormed: 1976,
};

Let's create an alias Band to refer to the object literal type:

type Band = {
  name: string,
  yearFormed: number,
};

const openingBand: Band = {
  name: 'Minutemen',
  yearFormed: 1980,
};

const headliningBand: Band = {
  name: 'Black Flag',
  yearFormed: 1976,
};

Now the type Band is shared across multiple objects.

Although aliasing a primitive is not terribly useful, it can be used as a form of documentation.

type Species = string;

const lizard: Species = 'Varanus niloticus';

Last updated