EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials TypeScript Tutorial TypeScript instanceof
Secondary Sidebar
TypeScript Tutorial
  • TypeScript Basic and Advanced
    • What is TypeScript?
    • Typescript Examples
    • TypeScript Versions
    • TypeScript Operators
    • JavaScript dump object
    • JavaScript get Method
    • Webpack ReactJS
    • Code Generator JavaScript
    • JavaScript Projects
    • Call Stack JavaScript
    • JavaScript Projects GitHub
    • JavaScript Filter Function
    • JavaScript nan
    • JavaScripttimestamp
    • TypeScript loop
    • CoffeeScript
    • TypeScript Webpack
    • setTimeout TypeScript
    • DHTMLX
    • CoffeeScript for loop
    • TypeScript number
    • JavaScript export module
    • TypeScript string contains
    • TypeScript Inheritance
    • TypeScript get
    • TypeScript undefined
    • TypeScript Global Variable
    • TypeScript Dictionary
    • TypeScript Generic
    • TypeScript Cast Object
    • TypeScript Optional Parameters
    • TypeScript? switch
    • TypeScript promise
    • TypeScript tuple
    • TypeScript Hashmap
    • TypeScript let
    • TypeScript Getter
    • TypeScript Pattern Matching
    • TypeScript number to string
    • TypeScript substring
    • TypeScript?lambda
    • TypeScript UUID
    • TypeScript JSDoc
    • TypeScript Decorators
    • Typescript for loop
    • TypeScript HTTP Request
    • TypeScript Abstract Class
    • TypeScript Question Mark
    • TypeScript Nullable
    • TypeScript reduce
    • TypeScript Mixins
    • TypeScript keyof
    • TypeScript string to number
    • TypeScript JSON parse
    • TypeScript const
    • TypeScript declare module
    • TypeScript String
    • TypeScript filter
    • TypeScript Multiple Constructors
    • TypeScript? Set
    • TypeScript string interpolation
    • TypeScript instanceof
    • TypeScript JSON
    • TypeScript Arrow Function
    • TypeScript generator
    • TypeScript namespace
    • TypeScript default parameter
    • TypeScript cast
    • TypeScript babel
    • Typescript Key-Value Pair
    • TypeScript if
    • TypeScript keyof Enum
    • TypeScript wait
    • TypeScript Optional Chaining
    • TypeScript JSX
    • TypeScript Version Check
    • TypeScript Unit Testing
    • TypeScript Handbook
    • TypeScript module
    • TypeScript Extend Interface
    • TypeScript npm
    • TypeScript pick
    • TypeScript Interface Default Value
    • JavaScript import module
    • Obfuscate Javascript
    • TypeScript basics
    • setInterval TypeScript
  • Type of Union
    • TypeScript Object Type
    • TypeScript type check
    • TypeScript promise type
    • TypeScript JSON type
    • TypeScript Union Types
    • TypeScript typeof
    • TypeScript Types
  • TypeScript Array
    • TypeScript Array of Objects
    • Methods TypeScript Array
    • TypeScript remove item from array
    • TypeScript add to array
    • TypeScript Array Contains
  • Function Of Array
    • TypeScript Function Interface
    • TypeScript Functions
    • TypeScript Export Function
    • TypeScript function return type

TypeScript instanceof

TypeScript instanceof

Introduction to TypeScript instanceof

The Typescript instanceof is one of the operators, and it is used to determine the specific constructor, and it will be creating the object of the classes. It will call the methods with the help of instance like that if we use an interface that can be implemented and extended through the classes. It will determine the property, and its chain will be added to the object it checks the actual condition of the prototype. It returns the Boolean conditions also the name of the variables on its left-hand side included the function of the classes.

Syntax

The instanceof operator is the keyword, and it is mainly used for the object to validate it’s a type or not, and it is followed up through the constructor function. The keyword uses and focuses on the class areas also, and it can be accessed and utilized in the variables, conditional statements, loops, etc.

function functionName(reference: class)
{
conditional statements(reference instanceof  another class)
{
----- some logics depends upon the user requirements --------
}
}

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

The above code is the basic syntax for utilizing the instanceof operator in the typescript classes. Using that instance, the methods are called for the specific class, which has been already declared on the class. Even the implementation of the interface is also being referred to the operator with the conditional statements.

How instanceof works in TypeScript?

In Typescript instanceof is one of the operators, and it takes the name of the variables on its left-hand side also the name of the function or class; the interface also initialized on the left side of the class. The instanceof operator is used to validate the objects at runtime whenever we want to create the objects at the specific classes; also, it always returns the boolean values like true or false statements if the required class need to create the instance and it requires to authenticate with the other code logics. Basically, the instanceof is the advanced type of the typescript; meanwhile, the operator is tested to see if the prototype property for the class-based constructors appears anywhere in the objects’ prototype chain.

The different scopes have a different set of executions in run time environments; also, it accepts compile-time scripts if the validation is failed for the specific class instance, then it throws the error in the compile-time itself sometimes the operator belongs to execute with the runtime mode in that it throws exceptions on the output console. While we evaluate the class reference using conditional statements, it validates the actual class instance and new class reference.

All in One Software Development Bundle(600+ Courses, 50+ projects)
Python TutorialC SharpJavaJavaScript
C Plus PlusSoftware TestingSQLKali Linux
Price
View Courses
600+ Online Courses | 50+ projects | 3000+ Hours | Verifiable Certificates | Lifetime Access
4.6 (86,818 ratings)

Examples of TypeScript instanceof

Different examples are given below:

Example #1

function demo(exam, exam1, exam2) {
this.exam = exam;
this.exam1 = exam1;
this.exam2 = exam2;
}
const demo1 = new demo('first', 'second', 'third');
console.log(demo1 instanceof demo);
console.log(demo1 instanceof Object);
function sample(vars, vars1, vars2, vars3, vars4, vars5, vars6, vars7){
this.vars = vars;
this.vars1 = vars1;
this.vars2 = vars2;
this.vars3 = vars3;
this.vars4 = vars4;
this.vars5 = vars5;
this.vars6 = vars6;
this.vars7=vars7;
}
const demo2 = new sample('four fsh35 hasd has has', 'secondfive', 'six', 'hs','js','sd','sde','sad sd swf fg fd');
console.log(demo2 instanceof demo);
console.log(demo2 instanceof Object);

Output:

TypeScript instanceof output 1

The above example shows the instanceof operator is used in one of the ways like that we can create the two methods like “demo” and “sample” for the two methods we can pass the set of arguments in each method. If we take the “demo()” method, it takes 3 arguments. In the same we can pass the values to the separate variable like that in the sample() method, multiple set of arguments are passing. Each argument value should be initialized with a separate variable type like “const” and creating a new object for the class using the “instanceof” operator; the class reference is validated and printed on the output console.

Example #2

interface demo {
example(): string;
}
class demo1 implements demo {
constructor(private ns: number) {}
example() {
return Array(this.ns + 1).join(" ");
}
}
class demo2 implements demo {
constructor(private vl: string) {}
example() {
return this.vl;
}
}
function examp() {
return Math.round(764.9834733746928374) < 10000000
? new demo1(79)
: new demo2("  ");
}
let pads: demo = examp();
if (pads instanceof demo1) {
console.log("Welcome To My Domain its a second example \n")
console.log(pads);
}
if (pads instanceof demo2) {
console.log("Welcome To My Domain its a second example \n")
console.log(pads)
}

Output:

TypeScript instanceof output 2

In the second example, we use additional classes and interfaces. Normally the interface is used to declare the methods or functions; it can’t be implemented with the help of classes; the interface methods are implemented and printed on the output console. Here we called some math functions like the round() method for validating the mathematical values also it compares another number. By using if conditional statement and instanceof operator, the classes are validated its types.

Example #3

class demo {
vars;
constructor(vars) {
this.vars = vars;
}
}
const examp = new demo('Welcome To My Domain jwegd qiwdkgds kjqcgsd kjGCDS CWGKDS');
console.log(examp instanceof demo);
console.log(Object.getPrototypeOf(examp) === demo.prototype);
console.log(examp instanceof Object);
console.log(Object.getPrototypeOf(demo.prototype) === Object.prototype);
console.log(examp instanceof class name {
});
console.log(Object.getPrototypeOf(demo.prototype) === Object.prototype);
console.log(examp instanceof Function);

Output:

TypeScript instanceof output 3

For the final example, we used the instanceof operator in the same ways as that already we used on the previous two examples. Additionally, we have used the operator with different ways of the console.log statement of the typescript like instanceof operator validate the types with Object, Function, other custom or user-defined method like “demo”. Here we also include the class name keyword for comparing the type using instanceof operator so that it creates the ‘{ and }’ open and close brackets for to implement the class name.

Rules and Regulations for instanceof

  1. The instanceof operator compares the class names, objects, functions and including other user-defined method types.
  2. It was also applicable for variables and other conditional statements for validating or comparing the two references.

Conclusion

The typescript language is generally used with many operators, keywords, and other pre-defined functions to implement the application in a more user-friendly nature. Like that instanceof operator will compare and validate the two object references, keywords, and other user-defined functions by using conditional statements it will be evaluated; finally, it returns the boolean value as the output console.

Recommended Articles

This is a guide to TypeScript instanceof. Here we discuss How instanceof works in TypeScript along with the examples and outputs. You may also have a look at the following articles to learn more –

  1. TypeScript typeof
  2. TypeScript Dictionary
  3. What is TypeScript?
  4. TypeScript Versions
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

C# Programming, Conditional Constructs, Loops, Arrays, OOPS Concept

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more