Narrowing

Type Script

October 15, 2022

Narrowing

The narrowing is moving a variable from a less precise type to a more accurate type. We can use type narrowing to avoid type errors.

Let's see the example:

Imaginge that we have a function usersHandler

Loading...

Inside the function we are initilaze random & transfoormRandomToUpperCase variable.

Loading...

As you can see, a random variable can be a type of string or array of numbers. We are dealing here with multiple types of the variable.

Loading...

Suppose we try to transform random variable to upperCase using javascript toUpperCase() function and assign the initialized value transfoormRandomToUpperCase. TypeScript will scream error.

Since we don't know if we will get it here, a string or a number, we can't be sure that this will be a string, and we will be able to call here function to toUpperCase().

Loading...

So we need to do NARROWING.

In the example below, we can narrow type specification is with a simple "Else IF statement." We can check if a variable random type is a string. We can use the "toUpperCase()" function to make a "random" string to the upper case.

Loading...

Ways to narrow types in TypeScript

Loading...

The narrowing is moving a variable from a less precise type to a more accurate type. We can use type narrowing to avoid type errors. TypeScript automatically narrows the type of a variable in conditional branches. Doing a truthly condition check will remove null and undefined from a type.

Join Our Discord Community Unleash your potential, join a vibrant community of like-minded learners, and let's shape the future of programming together. Click here to join us on Discord.

For Consulting and Mentorship, feel free to contact slavo.io

©2024. All rights reserved. Designed by Prototype.NEXT

slavo.io software development - Consultingslavo.io software development - Consulting slavo.io software development - Consulting