TypeScript 0.9.5:如何定义具有静态成员的接口和实现它的类?

 李辰1990 发布于 2023-02-05 11:30

这用于在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中,我得到编译器错误"Class LocalStorage声明接口ILocalStorage但不实现它".

我需要更改什么,以便再次编译?

注意:在此上下文中使用接口的原因是: - 具有实现的类的文档 - 让编译器检查接口是否正确实现.

1 个回答
  • 接口定义了类的实例,而不是类的实例.简而言之,您无法使用静态成员实现它.

    由于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 
    }
    

    2023-02-05 11:34 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有