Open In App

TypeScript Narrowing Assignments

Last Updated : 23 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

TypeScript narrowing assignments is a type of type inference mechanism that occurs when TypeScript examines the right side of an assignment and uses that information to narrow down the type of the variable or property on the left side of the assignment.

Syntax

let value: string | number = valueOftheVariable;

Parameters

  • value is the name of the variable
  • string|number is the type associated with the variable
  • valueOftheVariable is the actual value of the variable that needs to be assigned

Example 1: Assigning Different Types

In this example, we first assign a string to a variable and then a number. TypeScript allows this because the declared type of x is string | number. Assignability is always checked against the declared type. If we assigned a boolean to x, it would result in an error since that wasn’t part of the declared type.

JavaScript
let x: string | number = "Hello";
console.log(x); // Output: Hello

x = 42;
console.log(x); // Output: 42

// x = true; // Error: Type 'boolean' is not assignable to type 'string | number'.

Output:

Hello
42

Example 2: Narrowing in Function Parameters

In this example, we define a function printLengthOrValue that takes a parameter input with a type of string | number. Inside the function, we use the typeof operator to check the type of input. TypeScript narrows down the type of input within the conditional blocks.

JavaScript
function printLengthOrValue(input: string | number): void {
    if (typeof input === "string") {
        console.log(`Length of string: ${input.length}`);
    } else {
        console.log(`Value of number: ${input}`);
    }
}

printLengthOrValue("Hello"); // Output: Length of string: 5
printLengthOrValue(42);      // Output: Value of number: 42

Output:

Length of string: 5
Value of number: 42

Conclusion

In this article, we explored TypeScript narrowing assignments and their syntax. Narrowing assignments occur when TypeScript examines the right side of an assignment to narrow down the type of the variable or property on the left side. This type inference mechanism allows TypeScript to provide more accurate type information and perform type checking based on the actual values assigned, leading to safer and more robust code.


Next Article

Similar Reads