Language: EN

alias-en-typescript

Using Aliases in TypeScript

A Alias of type in TypeScript allows us to create an alternative name for a specific type (either standard or defined by us).

Aliases are a great help to improve code readability. They are especially useful when working with complex types (such as unions, intersections, and custom types).

Creating an alias

To create a type alias, the type keyword is used followed by the alias name and the type definition.

type AliasName = Type;

For example like this,

type ID = number;        // now ID is an alias for number
type Name = string;      // Name is an alias for string

let userID: ID = 123;
let userName: Name = "Luis Pérez";

console.log(userID); // 123
console.log(userName); // Luis Pérez

In this example,

  • ID is an alias for the type number
  • Name is an alias for the type string

Aliases with compound types

Type aliases are especially useful when combining types through unions or intersections.

Aliases with unions

In the following example, Result is a type that can either be a string or a number.

// We define a type alias 'Result' that can be a string or a number
type Result = string | number;

// We create a variable 'value1' with a text, and value2 with a number
let value1: Result = "Success";
let value2: Result = 200;

console.log(value1); // Success
console.log(value2); // 200

Aliases with intersections

In this example, UserEmployee is a type that combines two interfaces: User and Employee. This means that any object of type UserEmployee must have all the properties defined in both interfaces.

// We define a 'User' interface with properties 'name' and 'email'
interface User {
    name: string;
    email: string;
}

// We define an 'Employee' interface with properties 'employeeID' and 'department'
interface Employee {
    employeeID: number;
    department: string;
}

// We create a type alias 'UserEmployee' that combines the 'User' and 'Employee' interfaces
type UserEmployee = User & Employee;

// We create an object 'employee' that must fulfill both interfaces: 'User' and 'Employee'
const employee: UserEmployee = {
    name: "Ana García",
    email: "ana.garcia@example.com",
    employeeID: 101,
    department: "Development"
};

console.log(employee.name); // Ana García
console.log(employee.department); // Development

Aliases with literals

// We define a literal type 'State' that can only be one of the specific values
type State = 'active' | 'inactive' | 'pending';

// We create a variable 'userState' of type 'State' 
let userState: State = 'active';
console.log(userState); // active

// We change the value of 'userState' to another valid value
userState = 'pending';
console.log(userState); // pending

// Attempting to assign a disallowed value will cause a compilation error
userState = 'suspended'; // Error: Type '"suspended"' is not assignable to type 'State'.

Aliases with function types

Type aliases can also be used to define function types,

type Operation = (a: number, b: number) => number;

const add: Operation = (a, b) => a + b;
const subtract: Operation = (a, b) => a - b;

console.log(add(5, 3)); // 8
console.log(subtract(5, 3)); // 2

In this example, Operation is an alias for any function that takes two numbers as parameters and returns a number.

Aliases with generic types

Type aliases can be defined using generic parameters,

type Response<T> = {
    success: boolean;
    data: T;
    message?: string;
};

const response1: Response<string> = {
    success: true,
    data: "Operation successful"
};

const response2: Response<number> = {
    success: false,
    data: 0,
    message: "Error in operation"
};

console.log(response1.data); // Operation successful
console.log(response2.message); // Error in operation

In this example, Response is a generic type alias that can adapt to different data types.

Aliases and advanced types

Aliases and conditional types

Aliases can be combined with conditional types to create more dynamic and adaptive types.

type TextType<T> = T extends string ? "Is a string" : "Is not a string";

type TextResult = TextType<string>; // Is a string
type NumberResult = TextType<number>; // Is not a string

Aliases and mapped types

Aliases can be used with mapped types to transform other types.

type Optional<T> = {
    [P in keyof T]?: T[P];
};

interface User {
    name: string;
    email: string;
}

type OptionalUser = Optional<User>;

const user: OptionalUser = {
    name: "Carlos"
};

console.log(user.name); // Carlos
console.log(user.email); // undefined