【问题标题】:How do I type check Date in TypeScript?如何在 TypeScript 中输入检查日期?
【发布时间】:2019-10-07 12:53:25
【问题描述】:

instanceof Date === true 似乎不满足 TypeScript 3.4.5 的基于控制流的类型分析。在下面的代码中,TypeScript 会抱怨我返回的值不是 Date,即使在我检查它确实是 Date 之后也是如此。

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 firefox-addon-webextensions typescript3.0


    【解决方案1】:

    我认为您的问题不是您的 Typescript 版本,而是比较。不用=== true可以试试吗?

    if (testDate instanceof Date) {
        return testDate;
    }
    

    【讨论】:

    • 即使它是多余的,你有任何有效的论据来说明为什么会出现问题吗?
    • 我认为这与基于控制流的类型分析的工作方式有关。也许编译器只有在它只是if(x instanceof y) 时才识别它,并认为if(x instanceof y === true) 只是一个正常的比较。
    • 同意。这似乎是 TypeScript 编译器中的一个错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-03
    • 2020-01-24
    • 1970-01-01
    • 1970-01-01
    • 2015-09-03
    • 1970-01-01
    • 2021-05-23
    相关资源
    最近更新 更多