Type Alias in TypeScript

  • In TypeScript, a type alias allows you to create a new name for an existing type. It provides a way to create custom types that can be used interchangeably with existing types, making your code more expressive and easier to understand. Type aliases are especially useful when you have complex or lengthy types that you want to simplify or reuse in multiple places within your codebase.
  • To define a type alias in TypeScript, you use the `type` keyword followed by the new name and the existing type you want to alias. Here's the basic syntax:


    type AliasName = ExistingType;

Let's look at an example to illustrate how type aliases work.

  • Example 1:


    type newType = string | number | boolean
    // newType is a alias name

    let a: newType = 45
    console.log(a); // Output: 45

    let b: newType = "hello world"
    console.log(b); // Output: hello world

    let c: newType = true
    console.log(c); // Output: true

  • Example 2: Suppose you have an application that deals with coordinates, and you want to represent a point on a two-dimensional plane. You can define a type alias for the coordinates using an object literal:


    type Point = {
        x: number;
        y: number;
    };

  • In this case, `Point` is the type alias, and it represents an object with `x` and `y` properties, both of which have a type of `number`.
  • Now you can use the `Point` type alias to declare variables or function parameters:


    function drawPoint(point: Point) {
        console.log(`Drawing point at (${point.x}, ${point.y})`);
    }

    const p: Point = { x: 10, y: 20 };
    drawPoint(p);

  • In the code above, the `drawPoint` function expects a parameter of type `Point`, and the variable `p` is assigned a value that conforms to the `Point` type.
  • Type aliases can also be used with union types, intersection types, function types, and generic types.


    type ID = string | number;

    type Name = string;

    type Person = {
        id: ID;
        name: Name;
    };

  • Type aliases allow you to create more readable and reusable types in TypeScript, making your code easier to understand and maintain. They provide a convenient way to abstract complex types and improve the overall expressiveness of your code.

No comments:

Post a Comment