【问题标题】:How to declare an interface with static method?如何用静态方法声明接口?
【发布时间】:2016-02-16 14:40:49
【问题描述】:

我想在接口中声明一个替代构造函数 - baz in IFoo,但在 TypeScript 中似乎是不可能的:

interface IFoo {
    bar(): boolean;
    static baz(value): IFoo; 
}

class Foo implements IFoo {
    constructor(private qux) {}
    bar(): boolean {
        return this.qux; 
    }
    static baz(value): IFoo {
        return new Foo(value);
    }
}

有什么方法可以做到这一点并对baz进行适当的类型检查?

【问题讨论】:

标签: typescript


【解决方案1】:

您不能在 TypeScript 的接口中定义静态。如果您想对工厂方法进行类型检查,只需删除 static 关键字即可。

您仍然可以在 prototype 属性上使用这样的工厂方法:

var FootInstance = Foo.prototype.baz('test');

【讨论】:

    【解决方案2】:

    接口do not support 静态方法。

    can't use abstract classes也为你的问题:

    interface IFoo {
        bar(): boolean; 
    }
    
    
    abstract class FooBase {    
        abstract static baz(value): IFoo; // this is NOT allowed
    }
    
    
    class Foo extends FooBase {
        constructor(private qux) {
            super();
        }
    
        bar(): boolean {
            return this.qux; 
        }
        static baz(value): IFoo {
            return new Foo(value);
        }
    }
    

    【讨论】:

      【解决方案3】:

      你可以用匿名类做到这一点:

      一般情况

      export const MyClass: StaticInterface = class implements InstanceInterface {
      }
      

      你的例子:

      interface IFooStatic {
        baz(value): IFoo;
      }
      
      interface IFoo {
        bar(): boolean;
      }
      
      const Foo: IFooStatic = class implements IFoo {
        constructor(private qux) {}
        bar(): boolean {
          return this.qux; 
        }
        static baz(value): IFoo {
          return new Foo(value);
        }
      }
      

      【讨论】:

      • 不错的解决方案!
      • @chris 这似乎仍然是要走的路,经过 1.5 年的研究。我已经概括了你的解决方案:pastebin.com/v8Rf6g6Y你能评论一下那个实现吗?谢谢。
      • 嗯.. 但如果您需要从 Foo 继承似乎不起作用?
      • @shaunc 如果你想继承 Foo 并扩展它的接口,你可以创建一个扩展 IFooStatic 的新类型。不过,它确实有效。
      • @ReedSpool 你能举个例子吗?
      猜你喜欢
      • 1970-01-01
      • 2018-07-10
      • 2010-09-06
      • 1970-01-01
      • 2019-09-11
      • 2014-05-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多