Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript 0.9.5: how to define an interface with static members and a class that implements it?

Tags:

typescript

This used to compile in TypeScript 0.9.1.1 (method implementations omitted):

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

}

In TypeScript 0.9.5 I get compiler error "Class LocalStorage declares interface ILocalStorage but does not implement it".

What do I need to change, so that it compiles again?

Note: The reason to use an interface in this context was: - have documentation of what class implements - have the compiler check if interface is properly implemented.

like image 528
user1388173 Avatar asked Jan 08 '14 10:01

user1388173


1 Answers

Interface defines what instances of the class will have, not what the class has. So in short you cannot implement it with static members.

Since typeScript is structurally typed you can assign the class to the interface. In this case the class is effectively an instance :

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 
}
like image 172
basarat Avatar answered Oct 22 '22 09:10

basarat