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





