打字稿编译日期类型错误

Typescript compilation date type error

使用 typescript 1.4 我在以下代码行中遇到了有趣的错误:

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;
}

转译器returns如下:

[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.

与第 362 行和第 368 行的区别是我尝试解决问题的两种情况。

我在代码的其他地方使用了这个技巧,效果很好。

我包含了 lib.d.ts 中 Date 构造函数的定义以供参考:

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;

感谢@danludwig,从 datestring 的已知转换是 .toString()

if(typeof discount.dateTo ===  "string"){
    dateTo = new Date(discount.dateTo.toString());
} else {
    dateTo = discount.dateTo;
}

假设 discount.dateFrom 是一个联合类型,例如 string|Date,看起来您正试图在对象的 属性 上使用类型保护,而不是在普通类型上局部变量。不支持:

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

但是,如果您这样写:

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

然后应该工作。