1. What is Narrowing?
- The process of collapsing data types
- Using conditions to bind data types
- Helps to better understand data types => write safer code and avoid manipulation errors
2. Techniques:
The narrowing techniques in Typescript allow working with precise data types and provide automation for the data checking process, helping you to detect and correct errors quickly.
2.1 Type guards
Use typeof
, instanceof
, in
, or Array.isArray()
conditions to narrow down the return data type
Error because " ".repeat()
accepts number data, while we pass number | string
=> Right way
2.1.1 typeof
Type Guard
- How to check data type based on
typeof
- TS reports an error if the returned data type does not match the declared data type
When we check the condition that strs
is an object
data type or not, we can select string[]
as an array. But there is a problem that typeof
null is also object
. Therefore, Typescript can only narrow it down to the string[] | null
data type string[] | null
instead of null
as desired. However, we also have another way of checking called truthiness
checking.
2.1.2 Truth narrowing
- Here is how to shorten type based on
truthy
orfalsy
value - May lead to errors if the case is not handled properly
- Helps to write safer and more accurate code
Here, strs
is null
error like when using only typeof
by checking strs
. Alternatively, we can check with !
2.1.3 Equality narrowing
- Use
===
,!==
,==
,!=
- Type shortening based on a variable value
- Compare with a specific value
- Used for different types such as boolean, number, string or literal type
When checking the value of x
, y
. TS knows that their data types must also be equal. Therefore, TS also knows that x
and y
must be of type string
in the first branch
2.1.4 in
operator
- Check if a certain property exists in an object
2.1.5 instanceof
narrowing
- used to check if an object is created from a particular class
2.1.6 Using type predicates
- Helps us determine if a variable or value belongs to a particular type
- Shorten the data type of the variable or value, and can use the variable or value with a more precise data type.