alias-en-typescript

Using Aliases in TypeScript

  • 4 min

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

Aliases are a great help for improving 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;
Copied!

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
Copied!

In this example,

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

Aliases with compound types

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

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
Copied!

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
Copied!

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
Copied!

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
Copied!