// TypeScript中的静态函数的interface的变通实现方法 // 进一步参考:https://stackoverflow.com/questions/33719459/how-to-declare-an-interface-with-static-method?lq=1 /** * TypeScript Constructor Interfaces Proposal * * Author: Reed Spool */ /** * Root interface for Constructor Interfaces. This is a workaround for * TypeScript's lack of "static" methods for classes. * * Based on StackOverflow user chris's solution. See * https://stackoverflow.com/a/43484801/1037165 * * @interface IConstructor * @template InstanceInterface */ interface IConstructor { /** * Explicitly typed constructor is required, so make an extremely permissive * declaration that can be refined in subclasses. * * @constructor */ new (...args : any[]) : InstanceInterface; } /** * That's ALL for the definition. What follows is a comprehensive usage * example. */ // Create a Constructor Interface by extending IConstructor and // specifiying your Instance Interface. Keep your class open for // extension with "T extends ...". interface CMyClass extends IConstructor { // Specify constructor parameters safely, staying open for extension // by specifying any variatic arguments. You don't need to specify // a constructor though. new (instanceValue : string, ...args : any[]) : T; // Properties on Constructor Interfaces can be accessed by the // Class object. aClassProperty : string; // This is useful for static factory methods. aClassMethod () : T } // Create a normal Instance Interface. IConstructor doesn't require // or restrict anything here. You could use anything, including // `Object` or `any` interface IMyClass { } // This is the hackish part: Your class must be anonymous so that // you can specify the type of the variable that holds it. So make a // `const` variable of your Constructor Interface's type set to a new // anonymous class which implements your Instance Interface. export const MyClass : CMyClass = class implements IMyClass { // The constructor must satisfy CMyClass's `new` signature. constructor (instanceValue : string, ...args : any[]) { } // We can use the built-in JS `static` keyword to satisfy the interface // of CMyClass static aClassProperty : string = "myProp"; static aClassMethod () : IMyClass { return new MyClass(); } }