【问题标题】:TypeScript class with same name as interface与接口同名的 TypeScript 类
【发布时间】:2014-12-22 20:22:37
【问题描述】:

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

如果 Date 接口在模块中,我可以使用模块名称来区分,但它似乎在全局命名空间中。我的 Date 类在一个模块内。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    我相信没有特殊的关键字来访问全局命名空间,但以下工作:

    // 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”以避免这个问题(以及可能的混淆)。

    【讨论】:

    • 你确定这行得通吗?在我的 TypeScript 中,我无法像这样区分命名空间名称和我的类。附言。链接失效了
    猜你喜欢
    • 2017-08-20
    • 1970-01-01
    • 2019-06-27
    • 2018-07-26
    • 2018-09-22
    • 2020-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多