TypeScript – Type Guards


TypeScript – Type Guards


”;


In TypeScript, the type guards are used to determine a variable”s type, often inside a conditional or functional block. The type guards usually take the variable and return a Boolean value or the variable type. Type guards allow you to tell the TypeScript compiler to infer a given type for a variable in a specific context, guaranteeing that an argument”s type is what you say it is.

Similar to feature detection, type guards are commonly used to narrow down a type, enabling you to identify the appropriate prototypes, methods, and attributes of a value. As a result, handling that value become simple for the user.

The user-defined type guards can be created in TypeScript, but it also has built-in operators like the ”typeof”, ”in”, and the ”instanceof” operator.

The ”typeof” type guard in TypeScript

In TypeScript, the ”typeof” operator is used to get the type of the variable. According to the variable”s type, it returns the values like −

  • Number

  • String

  • Boolean

  • Object

  • Bigint

  • Symbol

  • Function

  • Undefined

Syntax

Users can follow the below syntax to use the ”typeof” type, guard operator.

typeof variable_name

In the above syntax, we use the typeof operator just before the variable name to get the variable type.

Example

In the following example, we will use the ”typeof” type guard in TypeScript. We have declared four variables of types” number”, ”string”, ”boolean”, and ”object”. After that, we console log their variable type using the ”typeof” operator of the TypeScript.

let my_number: number = 123
let my_string: string = ''Tutorialspoint''
let my_boolean: boolean = true
let my_object: { id: number } = { id: 1 }

console.log(''type of my_number variable is: '' + typeof my_number)
console.log(''type of my_string variable is: '' + typeof my_string)
console.log(''type of my_boolean variable is: '' + typeof my_boolean)
console.log(''type of my_object variable is: '' + typeof my_object)

On compiling, it will generate the following JavaScript code −

var my_number = 123;
var my_string = ''Tutorialspoint'';
var my_boolean = true;
var my_object = { id: 1 };
console.log(''type of my_number variable is: '' + typeof my_number);
console.log(''type of my_string variable is: '' + typeof my_string);
console.log(''type of my_boolean variable is: '' + typeof my_boolean);
console.log(''type of my_object variable is: '' + typeof my_object);

Output

The above code will produce the following output −

type of my_number variable is: number
type of my_string variable is: string
type of my_boolean variable is: boolean
type of my_object variable is: object

In the above output, users can see the output of the ”typeof” operator for four variables: ”number”, ”string”, ”boolean”, and ”object”.

The ”in” type guard in TypeScript

The ”in” type guard determines if an object contains a specific attribute, which is then used to distinguish between distinct types. It typically returns a boolean, indicating if the property is present in the object. It is utilized for its narrowing characteristics.

Syntax

Users can follow the below syntax to use the ”in” type guard operator.

property_name in object_name

In the above syntax, we use the ”in” operator to find whether the property exists in the object.

Example

In the following example, we will use the ”in” type guard in TypeScript. We have declared three objects that consist of different properties. We use the” in” type guard to check whether a required property exists in the object. We can even check if a property contains another property or if it is not using it. In the ”obj3”, we check if an object”s property contains another property or not.

let obj1: { id: number; name: string } = { id: 1, name: ''Tutorialspoint'' }
let obj2: { name: string; roll: number } = { name: ''XYZ'', roll: 12 }
let obj3: { id: number; marks: { english: number; math: number } } = {
   id: 101,
   marks: {
      math: 90,
      english: 80,
   },
}

console.log(''Is name in obj1? => '' + (''name'' in obj1))
console.log(''Is id obj2? => '' + (''id'' in obj2))
console.log(''Is marks in obj3? => '' + (''marks'' in obj3))
console.log(''Is math in obj3.marks? => '' + (''math'' in obj3.marks))

On compiling, it will generate the following JavaScript code −

var obj1 = { id: 1, name: ''Tutorialspoint'' };
var obj2 = { name: ''XYZ'', roll: 12 };
var obj3 = {
   id: 101,
   marks: {
      math: 90,
      english: 80
   }
};
console.log(''Is name in obj1? => '' + (''name'' in obj1));
console.log(''Is id in obj2? => '' + (''id'' in obj2));
console.log(''Is marks in obj3? => '' + (''marks'' in obj3));
console.log(''Is math in obj3.marks? => '' + (''math'' in obj3.marks));

Output

The above code will produce the following output −

Is name in obj1? => true
Is id in obj2? => false
Is marks in obj3? => true
Is math in obj3.marks? => true

In the above output, users can see the output of the ”in” operator in different circumstances in our code.

The ”instanceof” type guard in TypeScript

The ”instanceof” is a built-in type guard used to determine whether a value is an instance of a specific constructor function or class. We may use this type-guard to determine the type of instance type by testing if an object or value is derived from a class.

Syntax

Users can follow the below syntax to use the ”instanceof” type-guard operator.

object_name instanceof class_name

In the above syntax, we use the ”instanceof” operator to find whether the object is an instance of the class.

Example

In the following example, we will use the ”instanceof” type guard in TypeScript. We have declared a ”Parent” class and a child classe, ”Child”. We declare an objects of the ”Child” class and use the ”instanceof” operator to find the object belongs to which class.

class Parent {
   id: number
   constructor(id: number) {
      this.id = id
   }
}

class Child extends Parent {
   id: number
   name: string

   constructor(id: number, name: string) {
      super(id)
      this.name = name
   }
}

let child = new Child(101, ''ABC'')

console.log(''child instanceof Child => '' + (child instanceof Child))
console.log(''child instanceof Parent => '' + (child instanceof Parent))

On compiling, it will generate the following JavaScript code −

var __extends = (this && this.__extends) || (function () {
   var extendStatics = function (d, b) {
      extendStatics = Object.setPrototypeOf ||
         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
      return extendStatics(d, b);
   };
   return function (d, b) {
      extendStatics(d, b);
      function __() { this.constructor = d; }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
   };
})();
var Parent = /** @class */ (function () {
   function Parent(id) {
      this.id = id;
   }
   return Parent;
}());
var Child = /** @class */ (function (_super) {
   __extends(Child, _super);
   function Child(id, name) {
      var _this = _super.call(this, id) || this;
      _this.name = name;
      return _this;
   }
   return Child;
}(Parent));
var child = new Child(101, ''ABC'');
console.log(''child instanceof Child => '' + (child instanceof Child));
console.log(''child instanceof Parent => '' + (child instanceof Parent));

Output

The above code will produce the following output −

child instanceof Child => true
child instanceof Parent => true

In the above output, users can see the output of the ”instanceof” operator when used in different classes and their objects.

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *