我只是想在typescript接口中声明一个静态属性?我没有找到任何关于这方面的资料。

interface myInterface {
  static Name:string;
}

这可能吗?


当前回答

是的,这是可能的。这是解决方案

export interface Foo {

    test(): void;
}

export namespace Foo {

    export function statMethod(): void {
        console.log(2);
    }

}

其他回答

在TypeScript中,你不能在接口上定义静态属性。

假设您想要更改Date对象,而不是尝试添加到Date的定义中,您可以包装它,或者简单地创建富Date类来完成Date没有完成的工作。

class RichDate {
    public static MinValue = new Date();
}

因为Date是TypeScript中的一个接口,你不能使用extends关键字将它扩展为一个类,这有点遗憾,因为如果Date是一个类,这将是一个很好的解决方案。

如果你想扩展Date对象以在原型上提供MinValue属性,你可以:

interface Date {
    MinValue: Date;
}

Date.prototype.MinValue = new Date(0);

使用:

var x = new Date();
console.log(x.MinValue);

如果你想让它在没有实例的情况下可用,你也可以…但这有点繁琐。

interface DateStatic extends Date {
    MinValue: Date;
}

Date['MinValue'] = new Date(0);

使用:

var x: DateStatic = <any>Date; // We aren't using an instance
console.log(x.MinValue);

静态属性通常放在对象的(全局)构造函数上,而“interface”关键字适用于对象的实例。

如果你用TypeScript编写类,前面给出的答案当然是正确的。如果你描述的是一个已经在其他地方实现的对象,那么包含静态属性的全局构造函数可以这样声明:

declare var myInterface : {
  new(): Interface;
  Name:string;
}

简单的例子

interface Person {
  name: string;
  age: number;
}

abstract class Trackable {
  static TrackInstances: number;
}

class Pablo extends Trackable implements Person {
  constructor(public name: string, public age: number) { Pablo.TrackInstances+=1; }
}
console.log(Pablo.TrackInstances);

@duncan上面的解决方案为静态类型指定new()也适用于接口:

interface MyType {
    instanceMethod();
}

interface MyTypeStatic {
    new():MyType;
    staticMethod();
}

如果您正在寻找定义一个静态类(即。所有的方法/属性都是静态的),你可以这样做:

interface MyStaticClassInterface {
  foo():string;
}

var myStaticClass:MyStaticClassInterface = {
  foo() {
    return 'bar';
  }
};

在这种情况下,静态“类”实际上只是一个普通的-ol'-js-object,它实现了MyStaticClassInterface的所有方法