【问题标题】:TypeScript 0.9.5: how to define an interface with static members and a class that implements it?TypeScript 0.9.5:如何定义具有静态成员的接口和实现它的类?
【发布时间】:2014-01-26 08:50:29
【问题描述】:

这用于在 TypeScript 0.9.1.1 中编译(省略方法实现):

module MyNodule {
  export interface ILocalStorage {
    SupportsLocalStorage(): boolean;
    SaveData(id: string, obj: any): boolean;
    LoadData(id: string): any;
  }

  export class LocalStorage implements ILocalStorage {
    static SupportsLocalStorage(): boolean {
        return true;
    }

    static SaveData(id: string, obj: any): boolean {
        return true;
    }

    static LoadData(id: string): any {
        return {};
    }
  }

}

在 TypeScript 0.9.5 中,我收到编译器错误“类 LocalStorage 声明接口 ILocalStorage 但未实现它”。

我需要更改什么才能再次编译?

注意: 在这种情况下使用接口的原因是: - 有什么类实现的文档 - 让编译器检查接口是否正确实现。

【问题讨论】:

标签: typescript


【解决方案1】:

接口定义类的instances 将具有什么,而不是该类具有什么。所以简而言之,你不能用静态成员来实现它。

由于 typeScript 是结构化类型的,因此您可以将类分配给接口。在这种情况下,该类实际上是一个实例:

module MyNodule {
  export interface ILocalStorage {
    SupportsLocalStorage(): boolean;
    SaveData(id: string, obj: any): boolean;
    LoadData(id: string): any;
  }

  export class LocalStorage {
    static SupportsLocalStorage(): boolean {
        return true;
    }

    static SaveData(id: string, obj: any): boolean {
        return true;
    }

    static LoadData(id: string): any {
        return {};
    }
  }

  var foo : ILocalStorage = LocalStorage; // Will compile fine 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 2019-10-17
    • 2017-10-20
    • 2023-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多