liveBook · Manning

Type alias

As explained in Essential TypeScript 5, Third Edition

A type alias is a named TypeScript type definition that can represent an existing type or a composed type.

A type alias gives an existing type or combination of types a reusable name. Define one with `type`, a name, `=`, and the type definition. Use the name in annotations or assertions wherever the full definition would be cumbersome. An alias reduces repetition; it does not change how the TypeScript compiler treats the type. section 9.6

Name an object shape

In `src/todoCollection.ts`, `type ItemCounts = { total: number; incomplete: number };` names the shape of the object returned by `getItemCounts()`. Both properties must be numbers. The method can create its result with an ordinary JavaScript object literal; code in `src/index.ts` then reads `collection.getItemCounts().incomplete` to display the outstanding count. section 2.2.6

The same syntax works beyond a simple result object:

  • `type cities = "London" | "Paris" | "Chicago";` names a union of permitted values. `type cityResponse = `City: ${cities}`;` reuses it in a template literal type, avoiding a second city list. section 9.6
  • A `Product` alias can describe an object with a required `name`, an optional `price`, and an optional `hasFeature` method. `Product[]` then describes an array of objects matching that shape. section 10.2.3
  • A database schema alias can describe a `tasks` array whose entries have `id`, `task`, and `complete` properties. Applying it as `LowSync<schemaType>` lets the compiler check data read from Lowdb. section 2.5

An alias is also useful when JavaScript creates objects without a TypeScript class. A constructor function does not, by itself, give the compiler the object type needed in a type annotation. An alias can describe the resulting object's properties and prototype method. The alias may share the constructor function's name because type names and variable names are tracked separately. A property check with `in`, rather than `instanceof`, narrows the objects in this example. section 11.2

Listing 9.33 Using type aliases in the index.ts file in the src folder
function calculatePrice(quantity: 1 | 2, price: number): number {
    return quantity * price;
}

let total = calculatePrice(2, 19.99);
console.log(`Price: ${total}`);

type numVals = 1 | 2 | 3 | 4;

function  getRandomValue(): numVals {
    return Math.floor(Math.random() * 4) + 1 as numVals;
}

type cities = "London" | "Paris" | "Chicago";
type cityResponse = `City: ${ cities }`;

function getCityString(city: cities): cityResponse {
    return `City: ${city}`;
}

let str = getCityString("London");
console.log(str);

The `src/index.ts` listing shows aliases for a numeric union, a city union, and a template literal type, then uses them in function signatures and an assertion. section 9.6

How Essential TypeScript 5, Third Edition covers it

How deep it goes
Defines the syntax and works through several applications, while noting that an alias does not change compiler treatment.
Examples
Uses item counts, product arrays, city strings, a Lowdb task schema, and objects created by a constructor function.
What it assumes
Assumes familiarity with JavaScript object literals and functions, but defines type-alias syntax explicitly.
What you can do after
Apply it via TypeScript annotations and assertions to reuse type definitions and check shaped application data.
How it connects
Connects aliases to object shape types, literal unions, template literal types, generic type arguments, and type guards.

Also explained in

Compare how 6 books explain type alias →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Essential TypeScript 5, Third Edition. The section links point to the parts of the book it draws on.