TypeScript instanceof not working

前端 未结 3 2025
[愿得一人]
[愿得一人] 2020-12-17 22:01

I\'m having issues using the instanceof operator and it doesn\'t seem to work. Here is a part of my code:

        const results = _.map(items, function(item:         


        
相关标签:
3条回答
  • 2020-12-17 22:31

    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 object
    console.log(a);
    
    // {a:1}                 <-- the constructor type is empty
    //   a: 1
    //   __proto__: Object   <-- inherited from
    
    a instanceof A         // false because it is a plain object
    a 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" A
    console.log(a);
    
    // A {a:1}               <-- the constructor type is `A`
    
    a instanceof A         // true because it is constructed from A
    a 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()
    ];
    
    0 讨论(0)
  • 2020-12-17 22:32

    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*)
    
    0 讨论(0)
  • 2020-12-17 22:39

    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 };
    }
    
    0 讨论(0)
提交回复
热议问题