TypeScript instanceof not working TypeScript instanceof not working typescript typescript

TypeScript instanceof not working


instanceof will return true only if it matches the function or class from which it was constructed. The item here is a plain Object.

const a = { a: 1 } // plain objectconsole.log(a);// {a:1}                 <-- the constructor type is empty//   a: 1//   __proto__: Object   <-- inherited froma instanceof A         // false because it is a plain objecta instanceof Object    // true because all object are inherited from Object

If it is constructed using a constructor function or a class, then instanceof will work as expected:

function A(a) {    this.a = a;}const a = new A(1);    // create new "instance of" Aconsole.log(a);// A {a:1}               <-- the constructor type is `A`a instanceof A         // true because it is constructed from Aa instanceof Object    // true

If Goal is an Interface it will only check the structure of the object not its type. If Goal is a constructor then it should return true for instanceof checks.

Try something like:

// interface Goal {...}class Goal {...}        // you will have to change the way it works.items = [   new Goal()];

Update 2021:

Been playing with Typescript recently and came up with a better solution that works both in Typescript and JavaScript:

Try something like:

interface Goal {    getCount(): number;}class Goal implements Goal {    getCount() {        return 3;    }}function getItemCount(item: Goal | Note | Task) {    return item instanceof Goal ? item.getCount() : 'not a goal';}console.log(getItemCount(new Goal()));  // 3console.log(getItemCount('goal'));      // 'not a goal';

Here the interface and the class has the same name, so they can be used as both and type and an instance checker.

Changing the interface Goal signature or class Goal signature would throw something like:

TS2394: This overload signature is not compatible with its implementation signature.


You can also use type guards to your advantage:

https://basarat.gitbooks.io/typescript/docs/types/typeGuard.html

https://www.typescriptlang.org/docs/handbook/advanced-types.html

For instance, if you use a literal type guard to your class:

class Goal { type: 'goal'...}

then the check is as simple as :

if (item.type === 'goal') {}

Or you could write your own type guards:

function isNote(arg: any): arg is Note {    // because only your Note class has "content" property?    return arg.content !== undefined;}if (isNote(item)) {    result = { id: index, title: item.content.text };}


Try to instantiate the object with a constructor. It happened to me the same because I was manually mocking the object for testing purposes. If you create the item like following example, it should work:

item: Goal = new Goal(*item values*)