流类型:接口不能与联合类型组合

时间:2019-07-15 19:22:54

标签: javascript types flowtype

此示例使用接口并引发错误(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中。

1 个答案:

答案 0 :(得分: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