Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typescript MyObject.instanceOf()

Tags:

All of our typescript classes inherit (directly or indirectly) from:

export class WrObject {     className:string;      public instanceOf(name : String) : boolean {         return this.className === name;     } } 

We then declare a subclass as:

export class Section extends WrObject {     public static CLASS_NAME = 'Section';     className = Section.CLASS_NAME;          public instanceOf(name : String) : boolean {             if (this.className === name)                 return true;             return super.instanceOf(name);         }  } 

And you can then check with:

if (obj.instanceOf(Section.CLASS_NAME)) 

It all works great. However, I think it would be cleaner if we could do:

if (obj.instanceOf(Section)) 

Is there any way to do that? Or any suggestions as to a better approach?

thanks - dave

like image 623
David Thielen Avatar asked Jul 11 '14 20:07

David Thielen


People also ask

Does Instanceof work in TypeScript?

The instanceof operator can be used to help TypeScript narrow the type of a class object variable. It only works on class structures and not other TypeScript structures, such as interfaces.

What is difference between Typeof and Instanceof?

The typeof and the instanceof operator is quite different. typeof returns a type of entity that it's operated on. instanceof of returns true if an object is created from a given constructor and false otherwise. All non-primitive objects are instances of Object , so that'll always return true .

How do you check if an object is an instance of a particular class in JavaScript?

The JavaScript instanceof operator is used to check the type of an object at the run time. It returns a boolean value(true or false). If the returned value is true, then it indicates that the object is an instance of a particular class and if the returned value is false then it is not.

What is Instanceof in angular?

The instanceof operator tests to see if the prototype property of a constructor appears anywhere in the prototype chain of an object. The return value is a boolean value. Its behavior can be customized with Symbol.


2 Answers

If you are willing to accept the prototypal nature of JavaScript you can just use instanceof which checks the prototype chain:

class Foo{} class Bar extends Foo{} class Bas{}  var bar = new Bar();  console.log(bar instanceof Bar); // true console.log(bar instanceof Foo); // true console.log(bar instanceof Object); // true  console.log(bar instanceof Bas); // false 
like image 183
basarat Avatar answered Oct 14 '22 13:10

basarat


You can do it. Just replace your instanceOf implementation with this one:

public instanceOf(cls: { CLASS_NAME: string; }) {     return cls.CLASS_NAME === this.className || super.instanceOf(cls); } 
like image 37
Igorbek Avatar answered Oct 14 '22 13:10

Igorbek