【问题标题】:TypeScript: Specify the interface of the static part of an export class?TypeScript:指定导出类的静态部分的接口?
【发布时间】:2015-01-26 21:30:56
【问题描述】:

我尝试使用手册“Difference between static/instance side of class”部分下的技巧为类的静态端(即函数)指定接口:

export interface StaticInterface {
    info: string;
}
class _X {
    static info = 'something';
    ...
}
export var X: StaticInterface = _X;

但是当我尝试在另一个文件中 extend theModule.X 时,编译器会说:

error TS2305: Module '"..."' has no exported member 'X'.

【问题讨论】:

  • 您能否分享一个更完整的代码示例,以便我了解您要执行的操作?

标签: typescript


【解决方案1】:

这是一个基于 TypeScript 手册的工作示例:

module Example {
    export interface ClockStatic {
        new (hour: number, minute: number);
    }

    class Clock {
        currentTime: Date;
        constructor(h: number, m: number) { }
    }

    export var cs: ClockStatic = Clock;
}

var newClock = new Example.cs(7, 30);

导出接口并且类正确实现接口很重要。

【讨论】:

  • 您好,看来关键是接口中的构造函数定义。但是,我要使用的接口是一个也可以由普通实例实现的接口,所以这不会真正做到。新的错误是Cannot use 'new' with an expression whose type lacks a call or construct signature.
  • 您可能希望将实例接口和静态接口分开。例如,也许您希望它像 jQuery 一样工作,其中 JQueryStatic 接口返回一个实现 JQuery 接口的实例。
  • 是的。这样就可以了。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-23
  • 2020-03-06
  • 1970-01-01
  • 2012-07-31
  • 2017-05-31
相关资源
最近更新 更多