VOOZH about

URL: https://www.geeksforgeeks.org/typescript/typescript-narrowing-typeof-type-guards/

⇱ TypeScript Narrowing typeof type guards - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

TypeScript Narrowing typeof type guards

Last Updated : 30 Oct, 2023

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:

  • string
  • number
  • bigint
  • boolean
  • symbol
  • undefined
  • object
  • function

Syntax

if (typeof variable === 'type') {
 // Code to run when the variable
 // matches the specified type.
}

Where,

  • typeof: It is the TypeScript operator used to check the type of a variable.
  • variable: It is the variable whose type you want to check.
  • 'type': It is a string literal representing the expected type you want to check against.

Example 1: You can use typeof to check if a variable is of type string.


Output
GEEKSFORGEEKS

Example 2: You can use typeof to check if a variable is of type number.


Output
60

Example 3: You can use typeof to check if a variable is of type boolean.


Output
false

Example 4: You can use typeof to check if a variable is of type symbol.


Output
unique

Example 5: You can use typeof to check if a variable is undefined.


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


Output
person is an object
Name: GeeksforGeeks, Age: 30

Example 7: You can use typeof to check if a variable is a function.


Output
Hello!
Comment
Article Tags:

Explore