【问题标题】:Flow: Cannot assign _ to _ because property _ is missing in _流程:无法将 _ 分配给 _,因为 _ 中缺少属性 _
【发布时间】:2019-12-17 20:55:53
【问题描述】:

我在 try Flow 编辑器中重现了我的情况,可以访问here

这是链接发生问题时的代码:

/* @flow */

type PayloadType = 1 | 2 | 3;

type Transaction = {
  amount: number,
  destination: string
}

function create(type: PayloadType, transaction: Transaction): void {
  transaction.amount = 10;
  transaction.destination = "8ca76aff-8fe8-4715-9e9a-2ad0630d45a0"

  if ((type: PayloadType) === 4) {
    transaction.message = "Hello";
  }
}

const transaction: Transaction = {}
create(1, transaction)

错误是:

无法将"Hello!" 分配给transaction.message,因为在Transaction 1 中缺少属性message

我分配无效属性的行永远不应该被执行。我假设 Flow 应该知道这一点,因为 type 永远不会是 4,因此条件永远不会为真。

编辑:这是link 的一个更现实的例子。

【问题讨论】:

  • 什么情况会导致您编写不应该运行的错误类型代码?某种宏扩展?
  • Flow 也会报告transaction.message 赋值的错误,即使条件更改为if (false)。此外,如果您删除类型转换并只写if (type === 4),Flow 将正确地抱怨number literal 4 is incompatible with enum
  • 你知道为什么会报错if (false)吗?当它解析文本时会想到会忽略该语句。
  • 即使没有运行的代码也应该进行类型检查。这是它在几乎所有语言中的工作方式。那么,> 什么情况会导致您编写不应该运行的错误类型代码?某种宏扩展?
  • @Ry- 我添加了一个更接近我实际情况的示例。

标签: javascript flowtype


【解决方案1】:

我认为这里的问题不是那个错误出现,而是那个错误出现得太晚了,如果去掉if语句中type的强制转换会更早出现错误,我相信是更预期的结果。

/* @flow */

type PayloadType = 1 | 2 | 3;

type Transaction = {
  amount: number,
  destination: string
}

function create(type: PayloadType , transaction: Transaction): void {
  transaction.amount = 10;
  transaction.destination = "8ca76aff-8fe8-4715-9e9a-2ad0630d45a0"

  if (type === 4) {
    transaction.message = "Hello";
  }
}

const transaction: Transaction = {}
create(1, transaction)

Flow Try for change

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-05
    • 2019-06-18
    • 2019-07-05
    • 2019-07-15
    • 1970-01-01
    • 2018-11-10
    • 1970-01-01
    • 2019-11-24
    相关资源
    最近更新 更多