TypeScript
  • Introduction
  • Introduction
    • What is TypeScript?
    • Why TypeScript?
    • Setup
  • Beginner
    • Basic types
      • Primitive types
      • Arrays and tuples
      • Enums
      • Any type
    • Objects
    • Type aliases
    • Interfaces
    • Functions
      • Function signatures
      • Void type
      • Functions as types
    • Union types
    • Type guards
    • Intersection types
    • Nullable types
    • Inference
  • Resources
    • Resources
Powered by GitBook
On this page
  1. Beginner

Type aliases

PreviousObjectsNextInterfaces

Last updated 6 years ago

Type aliases are used to give a new name to an existing type. Type aliases can name , , , , , 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 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';
primitives
unions
functions
object literals
tuples
objects