如何在 TypeScript 中输入检查日期?
How do I type check Date in TypeScript?
instanceof Date === true
似乎不满足 TypeScript 3.4.5 基于控制流的类型分析。在下面的代码中,TypeScript 会抱怨我返回的值不是日期,即使我已经检查它确实是一个日期。
async function testFunction(): Promise<Date> {
const {testDate}: {testDate: Date | string} = await browser.storage.local.get({testDate: new Date()});
if (testDate instanceof Date === true) {
// typescript@3.4.5 will complain:
// Type 'string | Date' is not assignable to type 'Date'.
// Type 'string' is not assignable to type 'Date'.
return testDate;
} else if (typeof testDate === "string") {
return new Date(testDate);
}
}
我可以将有问题的行更改为 return testDate as Date
,但感觉我没有做正确的事。
我认为你的问题不是你的 Typescript 版本而是比较。没有=== true
可以试试吗?
if (testDate instanceof Date) {
return testDate;
}
instanceof Date === true
似乎不满足 TypeScript 3.4.5 基于控制流的类型分析。在下面的代码中,TypeScript 会抱怨我返回的值不是日期,即使我已经检查它确实是一个日期。
async function testFunction(): Promise<Date> {
const {testDate}: {testDate: Date | string} = await browser.storage.local.get({testDate: new Date()});
if (testDate instanceof Date === true) {
// typescript@3.4.5 will complain:
// Type 'string | Date' is not assignable to type 'Date'.
// Type 'string' is not assignable to type 'Date'.
return testDate;
} else if (typeof testDate === "string") {
return new Date(testDate);
}
}
我可以将有问题的行更改为 return testDate as Date
,但感觉我没有做正确的事。
我认为你的问题不是你的 Typescript 版本而是比较。没有=== true
可以试试吗?
if (testDate instanceof Date) {
return testDate;
}