使用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;
}
转换器返回以下内容:
[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行的区别在于我试图解决问题的两种情况。
我在代码的其他地方使用了这个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;
答案 0 :(得分:2)
假设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
}
然后应该工作。
答案 1 :(得分:0)
感谢@danludwig,从date
到string
的已知转换为.toString()
if(typeof discount.dateTo === "string"){
dateTo = new Date(discount.dateTo.toString());
} else {
dateTo = discount.dateTo;
}