【问题标题】:Javascript how do I document a variable that should be an Object of a specific typeJavascript如何记录应该是特定类型的对象的变量
【发布时间】:2020-06-19 08:16:06
【问题描述】:

我正在使用 WebStorm IDE。我有几个具有静态函数的类。例如,以下将打印“foo1_bar”到控制台。

class Foo {
    static bar() {
        return "foo_bar";
    }
}

class Foo1 extends Foo {
    static bar() {
        return "foo1_bar";
    }
}

class Foo2 extends Foo {
    static bar() {
        return "foo2_bar";
    }
}

/**
 * @param {Object} type
 */
const test=(type)=>{
    console.log(type.bar());
}
test(Foo1);

这行得通,IDE 说它是正确的,但我想指定给测试的对象必须是 Foo 类型。如果我将 Foo 放入 {} 而不是 Object 则失败。记录此内容的正确方法是什么?

【问题讨论】:

    标签: javascript parameters webstorm documentation


    【解决方案1】:

    @param 注释中的类型名称表示参数是相应类型的实例(即使用new type() 创建),因此仅解析实例成员。 你可以在这里尝试使用typeof

    class Foo {
        static bar() {
            return 'foo_bar'
        }
    }
    
    /**
     * @param {typeof Foo} type
     */
    const test = type => {
        console.log(type.bar()) //Unresolved function or method bar()
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用 TypeScript 检查type 的类型:

      例如:

      'use strict';
      
      class Foo {
      
          /**
           * Add property bar with no definite assignment assertion 
           * as bar is not defined in a constructor
           */ 
          bar!: typeof Foo.bar;
      
          static bar(): string {
              return "foo_bar";
          }
      }
      
      class Foo1 extends Foo {
          static bar(): string {
              return "foo1_bar";
          }
      }
      
      class Foo2 extends Foo {
          static bar(): string {
              return "foo2_bar";
          }
      }
      
      class Test {
          static bar(): string {
              return "foo_bar";
          }
      }
      
      class OneMore {
          static foo_bar(): string {
              return "foo_bar";
          }
      }
      
      /**
       * @param {Foo} type
       */
      const test = (type: Foo): void => {
          console.log(type.bar());
      }
      test(Foo); // Works
      test(Foo1); // Works
      test(Foo2); // Works
      test(Test); // Sadly works too..
      test(OneMore); // Fails
      

      之后的大部分代码都保持原样,除了设置返回类型和告诉 typescript 你的 bar 方法的类型。

      有一个缺点.. 如您所见,即使 Test 不是 typeof Foo,代码 test(Test) 也会正确编译。这是因为TestFoo 具有相同的结构,并且与Foo 静态兼容

      Pitfall: classes work structurally, not nominally

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-20
        • 1970-01-01
        • 2020-05-27
        • 1970-01-01
        相关资源
        最近更新 更多