【问题标题】:Flowtype: Interface can't be combined with union typeFlowtype:接口不能与联合类型结合
【发布时间】:2019-08-07 12:57:52
【问题描述】:

此示例使用接口并引发错误(try this example):

// @flow

interface ExtraField {
  note: string;
}

type Success = ExtraField & { success: true, value: boolean };
type Failed  = { success: false, error: string };

type Response = Success | Failed;

function handleResponse(response: Response) {
  if (response.success) {
    var value: boolean = response.value;
  } else {
    var error: string = response.error; // Error!
  }
}

错误是:

Cannot get `response.error` because: Either property `error` is missing in `ExtraField` [1]. Or property `error` is missing in object type [2]

注意事项

  1. 当从 interface 切换到 type 时,错误消失了,即将ExtraField 写为:

    type ExtraField = {
      note: string
    }
    
  2. @AluanHaddad 发现了另外两个奇怪的东西 (try the different cases here):

    • if (response.success) { 更改为if (!!response.success) { 时,错误将保留
    • 但是当将if (response.success) { 更改为if (response.success === true) { 时,错误将消失

我不太明白为什么interface 在这里不起作用。错误很奇怪。 error 字段未出现在 ExtraField 中。

【问题讨论】:

标签: javascript types flowtype


【解决方案1】:

Flow 中的交叉点类型似乎“严重损坏”(see this GitHub issue)。如果你使用对象类型传播,我认为这个例子应该更好。

// @flow
interface ExtraField {
  note: string,
}

type Success = { success: true, value: boolean };
type Failed  = { ...ExtraField, success: false, error: string };

type Response = Success | Failed;

function handleResponse(response: Response) {
  if (response.success) {
    var value: boolean = response.value;
  } else {
    var error: string = response.error;
  }
}

Try Flow

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-01
    • 2018-10-01
    • 1970-01-01
    相关资源
    最近更新 更多