Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript class with same name as interface

Tags:

typescript

I'd like to declare a class called Date which has a property of type Date (as in the TypeScript interface to the JavaScript Date object. However the compiler assumes my property is of the same type as the class I'm declaring. How can I distinguish between the two?

If the Date interface were in a module I could just use the module name to distinguish, however it seems to be in a global namespace. My Date class is inside a module.

like image 978
Adam H Avatar asked Oct 19 '22 23:10

Adam H


1 Answers

I believe there is no special keyword to access the global namespace, but the following works:

// 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());

See also: https://github.com/Microsoft/TypeScript/blob/master/src/lib/core.d.ts

In the past, I've always named such classes "DateTime" to avoid this problem (and possible confusion).

like image 136
Niko Avatar answered Oct 23 '22 23:10

Niko