![]() |
VOOZH | about |
In this article, we are going to learn about Narrowing typeof type guards. TypeScript is a popular programming language used for building scalable and robust applications. In TypeScript, the typeof type guard allows you to narrow down a variable's type based on the result of the typeof operator. This is particularly useful when dealing with primitive types like string, number, boolean, symbol, and undefined, and for checking if a variable is a function (function) or an object (object).
The following are the types that can be identified by typeof operator:
if (typeof variable === 'type') {
// Code to run when the variable
// matches the specified type.
}
Where,
Example 1: You can use typeof to check if a variable is of type string.
GEEKSFORGEEKS
Example 2: You can use typeof to check if a variable is of type number.
60
Example 3: You can use typeof to check if a variable is of type boolean.
false
Example 4: You can use typeof to check if a variable is of type symbol.
unique
Example 5: You can use typeof to check if a variable is undefined.
Value is undefined.
Example 6: This example checks the typeof Objects. It doesn't distinguish between different object types. Instead, it only tells you that a variable is not one of the other primitive types. We might need to use other type guards like instanceof or property existence checks to narrow down object types.
person is an object Name: GeeksforGeeks, Age: 30
Example 7: You can use typeof to check if a variable is a function.
Hello!