Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript compilation date type error

Tags:

typescript

Working with typescript 1.4 I'm having funny errors on the following code lines :

var dateFrom:Date;
var dateTo:Date;
if(typeof discount.dateFrom ===  "string"){
    dateFrom = new Date(discount.dateFrom); // Line 362
} else {
    dateFrom = discount.dateFrom;
}

if(typeof discount.dateTo ===  "string"){
    dateTo = new Date(<string>discount.dateTo); // Line 368
} else {
    dateTo = discount.dateTo;
}

The transpiler returns the following:

[FULL_PATH]/Quotation.ts(362,37): error TS2345: Argument of type 'Date' is not assignable to parameter of type 'string'.
[FULL_PATH]/Quotation.ts(368,35): error TS2352: Neither type 'Date' nor type 'string' is assignable to the other.

The difference from line 362 and 368 are two cases I tried to fix the issue.

I used this gimmic at other place in the code, and it worked fine.

I'm including the definition of the Date constructor from lib.d.ts for reference :

new (): Date;
new (value: number): Date;
new (value: string): Date;
new (year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date;
(): string;
like image 611
David Laberge Avatar asked Mar 03 '15 12:03

David Laberge


1 Answers

Assuming discount.dateFrom is a union type such as string|Date, it looks like you're trying to use a type guard on the property of an object, not on a plain local variable. That's not supported:

if (typeof discount.dateFrom === "string") {
    // This doesn't change the type of discount.dateFrom
}

However, if you write:

var dateFromProp = discount.dateFrom;
if (typeof dateFromProp === "string") {
    // dateFromProp is a string in this scope
}

Then should work.

like image 97
Daniel Earwicker Avatar answered Sep 25 '22 10:09

Daniel Earwicker