打字稿编译日期类型错误

Dav*_*rge 6 typescript

使用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;
}
Run Code Online (Sandbox Code Playgroud)

转换器返回以下内容:

[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.
Run Code Online (Sandbox Code Playgroud)

与线362和368的区别在于我试图解决问题的两种情况.

我在代码中的其他地方使用了这个gimmic,它运行正常.

我在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;
Run Code Online (Sandbox Code Playgroud)

Dan*_*ker 2

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

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

但是,如果你写:

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

然后应该可以工作。

  • @danludwig 联合类型在 1.4 中引入 http://blogs.msdn.com/b/typescript/archive/2014/11/18/what-s-new-in-the-typescript-type-system.aspx (2认同)