![]() |
When working with TypeScript, understanding how to check the type of an object is crucial for ensuring type safety and maintaining code integrity. TypeScript, being a statically typed superset of JavaScript, provides several approaches to accomplish this task as listed below. Table of Content Using the typeof OperatorThis operator returns a string indicating the type of the operand. We can operate this with the objects to check their type in TypeScript. Syntax:typeof variableName Example: The below example demonstrates how to use the typeof operator to determine the type of a variable.
Output: object Using the instanceof OperatorThis operator checks whether an object is an instance of a particular class or constructor. We can operate it by defining the testing object name before it and the class name after it. Syntax:objectName instanceof ClassName Example: The below example illustrates the usage of the instanceof operator to check if an object is an instance of a class.
Output: true Using Type GuardsType guards are functions that return a boolean indicating whether an object is of a specific type. Syntax:function isType(obj: any): obj is TypeName { Example: The below example demonstrates the implementation of a type guard function to check if an object satisfies a specific interface.
Output: Dog Using User-Defined Type PredicatesUser-defined type predicates in TypeScript provide a way to define custom logic to check whether a variable is of a specific type. By using the as keyword in the return type of a function, you can create a type predicate that helps TypeScript infer the type of an object. Example: The below example demonstrates how to create and use a user-defined type predicate to check if an object is of a specific type.
Output: true |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |