Horje
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

  • 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.

FAQs-TypeScript Narrowing Assignments

Can narrowing assignments handle union types?

Yes, narrowing assignments can refine union types by determining the specific type within the union using type guards and conditional checks.

How do typeof checks help in narrowing types?

typeof checks help in narrowing types by determining the runtime type of a variable, allowing TypeScript to refine the type accordingly, such as string, number, or boolean.

What are some common type guards used for narrowing types?

Common type guards include typeof, instanceof, and user-defined type predicates.

Can narrowing assignments prevent runtime errors?

Yes, narrowing assignments help prevent runtime errors by ensuring that variables are used in a type-safe manner, reducing the likelihood of type-related bugs.

How does TypeScript handle narrowing with null and undefined?

TypeScript narrows null and undefined types using strict null checks and conditional checks, ensuring these values are handled explicitly in the code.




Reffered: https://www.geeksforgeeks.org


Geeks Premier League

Related
TypeScript Uppercase<StringType> Template Literal Type TypeScript Uppercase<StringType> Template Literal Type
TypeScript Object Type Property Modifiers TypeScript Object Type Property Modifiers
Object Oriented System | Object Oriented Analysis & Design Object Oriented System | Object Oriented Analysis & Design
TypeScript Function TypeScript Function
TypeScript Assignability of Functions TypeScript Assignability of Functions

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
15