Jared
Jared

Reputation: 6090

Use Datejs in TypeScript

How would you tell TypeScript to use Datejs as Date instead of the builtin Date object?

I tried adding a reference to the js file and declaring Date as type any i.e. declare var Date: any; but this did nothing to fix the error.

EDIT: I found this question, but it talks about specifying a method to include. I'm wondering if it's possible to leave it open ended and simply turn off type checking for Date;

Upvotes: 1

Views: 5003

Answers (3)

Richard Collette
Richard Collette

Reputation: 5713

Install the package 'datejs.typescript.definitelytyped' from nuget

http://www.nuget.org/packages/datejs.TypeScript.DefinitelyTyped/

Add a reference to the type file. In a global script file declare a global variable, or in a class declare either a private static member variable or simply a local variable, assigning as shown in the code below.

/// <reference path="typings/datejs/datejs.d.ts" />
var DateJs: IDateJSStatic = <any>Date;

I'm currently writing SPA applications so I use a global variable as shown in the code example.

Upvotes: 1

Fenton
Fenton

Reputation: 251242

To get you started with extending the native date, it would look like this:

interface DateIs {
    monday(): bool;
    // ctd...
    january(): bool;
    // ctd...
    weekday(): bool;
}

interface DateAdd {
    days(): Date;
    months(): Date;
    // ctd...
}

interface Date {
    parse(date: string): Date;
    today(): Date;
    next(): Date;
    last(): Date;
    monday(): Date;
    // ctd...
    january(): Date;
    // ctd...
    addDays(days: number): Date;
    addMonths(months: number): Date;
    add(quantity: number): DateAdd;
    is(): DateIs;
}

With this example, you could continue to add the functions you use, I have put in one month as an example so you could fill in february() and also the short jan() variations as you see fit!

Upvotes: 7

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 221342

There isn't a way to take an existing variable with a type (Date in this case) and turn it in to an any.

The best option would be to extend the Date interface with the new methods from datejs. Hopefully at some point someone will do this and upload it to DefinitelyTyped.

Two workarounds you could do:

var Date2 = <any>Date;
// Use Date2 anywhere you would use Date

The other workaround would be to just modify lib.d.ts to declare Date as any. Obviously this will have side effects everywhere, but would work.

Upvotes: 6

Related Questions