Open In App

TypeScript Narrowing Assignments

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:

Example 1: In this example, we will first assign a string to a value. We can now even assign numbers to values. This is because the declared type of x – the type that x started with – is string | number and assignability are always checked against the declared type. If we’d assigned a boolean to x, we’d have seen an error since that wasn’t part of the declared type.






let value: string | number = "GeeksforGeeks";
  
console.log("Assigned Valid String value " + value)
value = 22;
console.log("Assigned Valid String value " + value)
//value=true is invalid

Output:



Example 2: In this example,We define a function printLengthOrValue that takes a parameter input with a type of string | number. Inside the function, we check the type of input using the typeof operator.If input is of type “string”, we print the length of the string using input.length. TypeScript narrows down the type of input to string within the if block. If input is not a string (i.e., it’s of type “number” or anything else), we simply print its value as a number. TypeScript narrows down the type of input to number within the else block.




function printLengthOrValue(
        input: string | number): void {
    if (typeof input === "string") {
        console.log(`Length of the string: ${input.length}`);
    } else {
        console.log(`Value of the number: ${input}`);
    }
}
  
printLengthOrValue("Hello, GeeksforGeeks!!");
printLengthOrValue(42);

Output:

Conclusion: In this article, we have seen Typescript narrowing assignmnets and it’s syntax. 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 This helps TypeScript provide more accurate type. information and perform type checking based on the actual values assigned.

Reference: https://www.typescriptlang.org/docs/handbook/2/narrowing.html#assignments


Article Tags :