首页 > 解决方案 > 与不相交的工会感到困惑

问题描述

我正在尝试合并可能的对象并将一个对象转换为另一个对象

但是打字稿和流程都无法识别布尔值是真还是假,没有别的,可以将布尔值分配给需要以太真文字或假文字的对象洋葱

type Aa = {
  isFetching: false,
  isFailed: false,
  isFetched: false
}

type Bb = {
  isFetching: true,
  isFailed: false,
  isFetched: false
}

type Cc = {
  isFetching: true,
  isFailed: true,
  isFetched: false
}
type Dd = {
  isFetching: false,
  isFailed: true,
  isFetched: false
}

type Data = Aa | Bb | Cc | Dd

function thisWorks(data: Data): Data {
  if (data.isFailed) {
    return {
      isFetching: true,
      isFailed: true,
      isFetched: data.isFetched
    }
  } else {
    return {
      isFetching: true,
      isFailed: false,
      isFetched: data.isFetched
    }
  }
}

function thisDoesNot(data: Data): Data {
  return {
    isFetching: true,
    isFailed: data.isFailed,
    isFetched: data.isFetched
  }
}

这是不是这个错误?

flow.org/try

打字稿游乐场

标签: javascripttypescriptflowtype

解决方案


问题是对象文字既不兼容Bbor Cc,因为isFailedis boolean(因为该字段对联合的所有成员都是通用的,它将变成true|falsewhich is booelan

最简单的解决方案是对联合使用类型断言。这将保留一些检查,但允许分配发生:

function thisDoesNot(data: Data): Data {
    return {
        isFetching: true,
        isFailed: data.isFailed,
        isFetched: data.isFetched
    } as Data
}

这将是一个错误:

function thisDoesNot(data: Data): Data {
    return {
        isFetching: 1,
        isFailed: data.isFailed,
        isFetched: data.isFetched
    } as Data
}

但是,我们确实会丢失多余的财产检查,这将是有效的:

function thisDoesNot(data: Data): Data {
    return {
        excess: 1,
        isFetching: true,
        isFailed: data.isFailed,
        isFetched: data.isFetched
    } as Data
}

推荐阅读