typescript 如何使用静态方法声明接口?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33719459/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:07:55  来源:igfitidea点击:

How to declare an interface with static method?

typescript

提问by Gill Bates

I want to declare an alternative constructor in interface - bazin IFoo, but seems like it's impossible in TypeScript:

我想在 interface - bazin 中声明一个替代构造函数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);
    }
}

What is the way to do that and have a proper type checking for baz?

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

回答by chris

you can do this with anonymous classes:

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

In general

一般来说

export const MyClass: StaticInterface = class implements InstanceInterface {
}

Your example:

你的例子:

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);
  }
}

回答by Martin Vseticka

Interfaces do not supportstatic methods.

接口不支持静态方法。

You can't use abstract classesfor your problem too:

也不能为您的问题使用抽象类

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);
    }
}

回答by FlorianTopf

You can't define a static in an interface in TypeScript. If you want to have type checking for the factory method just remove statickeyword.

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

You can still use the factory method like this over the prototypeproperty:

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

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

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