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 keyword type is used followed by the alias name and the type definition.

type AliasName = Type;

For example:

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 = "Juan Pérez";

console.log(userID); // 123
console.log(userName); // Juan 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 be either 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 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 an interface 'User' with properties 'name' and 'email'
interface User {
    name: string;
    email: string;
}

// We define an interface 'Employee' 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

// Trying 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: "Operation error"
};

console.log(response1.data); // Operation successful
console.log(response2.message); // Operation error

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