Introduction
A variable is a uniquely named location used to store data in any programming language. In Typescript, the variable must be declared before being used, using the keyword let or var. The syntax for declaring variables in Typescript is a little different from other languages and looks something like this,
var [variable_name] : [type_of_variable] = [value] ;
For example
var name: string = “Ninja”; //Both the value and the type is specified
var name: string; //only the type is mentioned
var name = “Ninja”; //only the value is mentioned
var name; //neither the value nor the type is mentioned, only the variable is declared
All of these are correct methods of initializing a variable.
Type Narrowing refers to the process of moving a variable from a less precise data type to a more exact data type. Type Narrowing can be implemented in many ways, and we will look at all of them in this article. For example, if no data type is mentioned, the variable will be allotted any type.
Type Guards
Type Guards are the most commonly used tools to achieve Type Narrowing. It is used to check whether a variable is a certain type or not. Let us look at an example to understand Type Guards better,
function Narrow(input: string | number){
if(typeof input === "string"){
console.log("Input is a string");
}
else{
console.log("Input is a number");
}
};
Narrow("Hey Ninja");
Narrow(1111);
The input could take either a string or a number type in the above example. Using Type Guards, we performed Narrowing, such that when the input type is a string, the if block is executed. Otherwise, we move to the else block.
We can also implement it to differentiate between a truthy or falsy i.e. Null or Undefined, data types. Let us look at an example,
function Narrow(input?:string){
if(input){
console.log("Input is a string");
}
else{
console.log("Input is undefined");
}
};
Narrow("Hey Ninja");
Narrow();