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.
Javascript
const p = 'GeeksforGeeks' ;
if ( typeof p === 'string' ) {
console.log(p.toUpperCase());
}
|
Example 2: You can use typeof to check if a variable is of type number.
Javascript
const age = 30;
if ( typeof age === 'number' ) {
console.log(age * 2);
}
|
Example 3: You can use typeof to check if a variable is of type boolean.
Javascript
const isTrue = true ;
if ( typeof isTrue === 'boolean' ) {
console.log(!isTrue);
}
|
Example 4: You can use typeof to check if a variable is of type symbol.
Javascript
const uniqueSymbol = Symbol( 'unique' );
if ( typeof uniqueSymbol === 'symbol' ) {
console.log(uniqueSymbol.description);
}
|
Example 5: You can use typeof to check if a variable is undefined.
Javascript
let someValue;
if ( typeof someValue === 'undefined' ) {
console.log( 'Value 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.
Javascript
const person = {
name: 'GeeksforGeeks' ,
age: 30,
};
if ( typeof person === 'object' ) {
console.log( 'person is an object' );
console.log(`Name: ${person.name}, Age: ${person.age}`);
}
|
Output
person is an object
Name: GeeksforGeeks, Age: 30
Example 7: You can use typeof to check if a variable is a function.
Javascript
function greet() {
console.log( 'Hello!' );
}
if ( typeof greet === 'function' ) {
greet();
}
|
Share your thoughts in the comments
Please Login to comment...