代码之家  ›  专栏  ›  技术社区  ›  sasensi

特定javascript实例化模式的正确类型脚本定义是什么

  •  2
  • sasensi  · 技术社区  · 8 年前

    Paper.js

    这种情况可以简化为以下几点:假设我们有一个 Animal 具有静态属性的类 Dog

    var Animal = function(type) {};
    Animal.Dog = function() {
        return new Animal('dog');
    };
    

    一 动物 实例可以通过两种方式构建:

    var dog = new Animal('dog');
    

    var dog = new Animal.Dog();
    

    在这两种情况下,我都需要 dog 动物 .


    declare class Animal
    {
        constructor ( type )
        static Dog (): Animal
    }
    

    但是TSLint失败了,错误是:“只能用'new'关键字调用void函数。” Animal.Dog() 动物 .

    如果我设置了 动物狗 void :

    declare class Animal
    {
        constructor ( type )
        static Dog (): void
    }
    

    无效的


    所以我尝试了另一种方法:

    declare class Animal
    {
        constructor ( type )
    }
    
    declare namespace Animal
    {
        export class Dog extends Animal
        {
            constructor()
        }
    }
    

    在这种情况下,TSLint通过,但在以下情况下:

    推断的类型 狗 变量是 Animal.Dog 而不是 动物 如我所愿。

    动物,狗 类型扩展 动物 动物,狗 在库中,因此我发现此解决方案对用户有误导性。

    从@stramski解决方案开始,我向问题添加了一个事实,即 动物狗 和 Animal.Dog(color) )我的目标是分别记录它们。

    2 回复  |  直到 8 年前
        1
  •  3
  •   Stramski    8 年前

    像这样的东西怎么样:

    declare class Animal
    {
        constructor ( type )
        static Dog : (new () => Animal)
    }
    

    由于存在重载构造函数,因此类型略有不同:

    declare class Animal
    {
        constructor ( type )
        static Dog : (new () => Animal) & (new (color) => Animal)
    }
    
        2
  •  0
  •   Fallenreaper    8 年前

    因为您是子类化的。。保持事物的整洁和简洁是很重要的。按照上面写的方式,你可以看到狗是由动物创造的,但它和动物没有区别。在某些情况下,有些变量或方法被重写。话虽如此,我发现如果您实施类似于以下内容的内容会更好:

    class Animal {
      constructor(){}
      communicate() { return "Makes Noise"; }
    }
    
    class Dog extends Animal {
      constructor(){
        super();
      }
    
      communicate() { return "Barks"; }
    }
    

    从那里,您可以重写方法或变量,以便正确区分狗和动物,以及其他动物子类。