Literals Type in TypeScript

  • In TypeScript, a literal type allows you to specify that a variable or parameter must have a specific value, rather than just a specific type. It is a type that represents a single value, and that value is treated as the only possible value for that type.
  • Literal types are created by using literal values as types, such as string literals, number literals, boolean literals, or even custom literals.
Here's an example to demonstrate the concept of literal types:


    function displayStatus(status: "active" | "inactive") {
        console.log(`The status is: ${status}`);
    }

    displayStatus("active");   // Output: The status is: active
    displayStatus("inactive"); // Output: The status is: inactive
    displayStatus("pending");  // Error: Argument of type '"pending"' is not assignable to parameter of type '"active" | "inactive"'

  • In the above example, the `displayStatus` function accepts a parameter `status` of type "active" | "inactive". This means that the `status` parameter can only have the literal values "active" or "inactive", and no other values are allowed.
  • When calling the `displayStatus` function with the literal value `"active"`, the function executes successfully and prints the status as `"active"`. Similarly, when called with the literal value `"inactive"`, the function prints the status as `"inactive"`.
  • However, if you try to call the `displayStatus` function with a different literal value like "pending", it will result in a compilation error. This is because the "pending" literal is not assignable to the literal type "active" | "inactive".
  • Literal types are particularly useful when you want to narrow down the possible values of a variable or parameter to a specific set of known values. They provide compile-time guarantees by restricting the allowed values, and TypeScript can use this information for type checking and inference.
  • You can combine literal types with other TypeScript features like union types, type guards, and pattern matching to create more complex and precise types in your code.

No comments:

Post a Comment

Primitive Types in TypeScript

In TypeScript, primitive types are the most basic data types, and they are the building blocks for handling data. They correspond to simple ...