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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With