Open In App

What is Type Narrowing in TypeScript ?

Last Updated : 23 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Type narrowing is a process of refining or narrowing down the type using certain conditions with a particular code block. It will help developers as well as TypeScript itself to infer the more accurate types within the code and work with them in a clean and strict code environment. The type narrowing can be done using the type guards(typeof, instanceof operator), equality operators(==, ===), etc.

Syntax:

typeof variable === another comparing type;

Example: The below code will explain the use of the typeof operator to narrow the type in TypeScript.

Javascript




function typeNarrowing(arg: any): boolean {
  return typeof arg === 'number';
}
 
typeNarrowing(20099) ?
console.log("Type is narrowed to number") :
console.log("Type can not be narrowed to number");
 
typeNarrowing("GeeksforGeeks") ?
console.log("Type is narrowed to number") :
console.log("Type can not be narrowed to number");


Output:

Type is narrowed to number
Type can not be narrowed to number

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads