Javascript 如何记录一个应该是特定类型对象的变量

Javascript how do I document a variable that should be an Object of a specific type

我正在使用 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 中,它就会失败。记录这个的正确方法是什么?

您可以使用 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

之后的大部分代码保持原样,除了设置 return 类型和告诉打字稿你的 bar 方法的类型。

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

Pitfall: classes work structurally, not nominally

@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()
}