我想声明一个名为Date的类,该类具有日期类型的属性(如JavaScript Date object的TypeScript接口(interface)。但是,编译器假定我的属性与我要声明的类具有相同的类型。我如何区分两者?

如果Date接口(interface)位于模块中,则可以使用模块名称来区分,但是它似乎位于全局 namespace 中。我的Date类在模块内部。

最佳答案

我相信没有特殊的关键字可以访问全局 namespace ,但是可以进行以下工作:

// Create alias (reference) to the global Date object
var OriginalDate = Date;

// Make copy of global Date interface
interface OriginalDate extends Date {}

module Foo {
    export class Date {
        public d: OriginalDate; // <-- use alias of interface here
        constructor() {
            this.d = new OriginalDate(2014, 1, 1); // <-- and reference to object here
        }
    }
}

var bar = new Foo.Date();
alert(bar.d.getFullYear().toString());

另请参阅:https://github.com/Microsoft/TypeScript/blob/master/src/lib/core.d.ts

过去,我总是将此类命名为“DateTime”,以避免出现此问题(并可能造成困惑)。

关于与接口(interface)名称相同的TypeScript类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26591245/

10-13 07:46
查看更多