
- TypeScript - Home
- TypeScript - Roadmap
- TypeScript - Overview
- TypeScript - Environment Setup
- TypeScript - Basic Syntax
- TypeScript vs. JavaScript
- TypeScript - Features
- TypeScript - Variables
- TypeScript - let & const
- TypeScript - Operators
- TypeScript - Types
- TypeScript - Type Annotations
- TypeScript - Type Inference
- TypeScript - Numbers
- TypeScript - Strings
- TypeScript - Boolean
- TypeScript - Arrays
- TypeScript - Tuples
- TypeScript - Enums
- TypeScript - Any
- TypeScript - Never
- TypeScript - Union
- TypeScript - Literal Types
- TypeScript - Symbols
- TypeScript - null vs. undefined
- TypeScript - Type Aliases
- TypeScript Control Flow
- TypeScript - Decision Making
- TypeScript - If Statement
- TypeScript - If Else Statement
- TypeScript - Nested If Statements
- TypeScript - Switch Statement
- TypeScript - Loops
- TypeScript - For Loop
- TypeScript - While Loop
- TypeScript - Do While Loop
- TypeScript Functions
- TypeScript - Functions
- TypeScript - Function Types
- TypeScript - Optional Parameters
- TypeScript - Default Parameters
- TypeScript - Anonymous Functions
- TypeScript - Function Constructor
- TypeScript - Rest Parameter
- TypeScript - Parameter Destructuring
- TypeScript - Arrow Functions
- TypeScript Interfaces
- TypeScript - Interfaces
- TypeScript - Extending Interfaces
- TypeScript Classes and Objects
- TypeScript - Classes
- TypeScript - Objects
- TypeScript - Access Modifiers
- TypeScript - Readonly Properties
- TypeScript - Inheritance
- TypeScript - Static Methods and Properties
- TypeScript - Abstract Classes
- TypeScript - Accessors
- TypeScript - Duck-Typing
- TypeScript Advanced Types
- TypeScript - Intersection Types
- TypeScript - Type Guards
- TypeScript - Type Assertions
- TypeScript Type Manipulation
- TypeScript - Creating Types from Types
- TypeScript - Keyof Type Operator
- TypeScript - Typeof Type Operator
- TypeScript - Indexed Access Types
- TypeScript - Conditional Types
- TypeScript - Mapped Types
- TypeScript - Template Literal Types
- TypeScript Generics
- TypeScript - Generics
- TypeScript - Generic Constraints
- TypeScript - Generic Interfaces
- TypeScript - Generic Classes
- TypeScript Miscellaneous
- TypeScript - Triple-Slash Directives
- TypeScript - Namespaces
- TypeScript - Modules
- TypeScript - Ambients
- TypeScript - Decorators
- TypeScript - Type Compatibility
- TypeScript - Date Object
- TypeScript - Iterators and Generators
- TypeScript - Mixins
- TypeScript - Utility Types
- TypeScript - Boxing and Unboxing
- TypeScript - tsconfig.json
- From JavaScript To TypeScript
- TypeScript Useful Resources
- TypeScript - Quick Guide
- TypeScript - Cheatsheet
- TypeScript - Useful Resources
- TypeScript - Discussion
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.