![]() |
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. Syntaxlet value: string | number = valueOftheVariable; Parameters
Example 1: Assigning Different TypesIn 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.
Output: Hello Example 2: Narrowing in Function ParametersIn 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.
Output: Length of string: 5 ConclusionIn 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 AssignmentsCan narrowing assignments handle union types?
How do typeof checks help in narrowing types?
What are some common type guards used for narrowing types?
Can narrowing assignments prevent runtime errors?
How does TypeScript handle narrowing with null and undefined?
|
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 15 |