admin管理员组

文章数量:1287627

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;

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;

Share Improve this question edited May 23, 2017 at 11:54 CommunityBot 11 silver badge asked Jan 14, 2013 at 20:03 JaredJared 6,0809 gold badges52 silver badges88 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

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!

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.

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

http://www.nuget/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.

本文标签: javascriptUse Datejs in TypeScriptStack Overflow