【问题标题】:Flow: Date is incompatible with string流:日期与字符串不兼容
【发布时间】:2019-06-15 15:45:30
【问题描述】:
import is from "is_js";
function handle_date_string(dateObj: Date | string): string {
  const result = is.date(dateObj) ? dateObj.toDateString() : dateObj;
  return result;
}

此函数的作用 - 如果它接收到 Date 对象,则将其转换为日期字符串,否则传递接收到的字符串。
Flow 报告以下错误:

错误:(21, 45) 无法调用 dateObj.toDateString,因为在 String [1] 中缺少属性 toDateString
错误:(22, 10) 无法返回 result,因为 Date [1] 与字符串 [2] 不兼容。

【问题讨论】:

    标签: javascript flowtype


    【解决方案1】:

    Flow 无法推断 is.date() 保证第一个分支中的 dateObj 将是 Date 对象。请改用dateObj instanceof Date ? ...

    【讨论】:

    • hmm... 还有其他方法可以使用is.js 吗?使用该库的全部意义在于摆脱 typeofinstanceof 检查。我什至将 is.js 定义从肯定类型转换为流类型,但流仍然不开心
    • 根据this issue thread,用于类型细化的自定义谓词函数似乎是不可能的。您可以编写自己的 isDate 函数来使用 %checksinstanceof,但是,正如您所提到的,这违背了使用 is.js 的目的。
    猜你喜欢
    • 1970-01-01
    • 2018-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-14
    • 1970-01-01
    • 1970-01-01
    • 2018-08-30
    相关资源
    最近更新 更多