与不连贯的工会相混淆

时间:2018-10-08 14:39:38

标签: javascript typescript flowtype

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

但是打字稿和流程都无法识别布尔值是对还是错,并且别无其他选择,可以将布尔值分配给需要以太真或假的实心对象的洋葱

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

typescript Playground

1 个答案:

答案 0 :(得分:1)

问题在于对象文字与BbCc都不兼容,因为isFailedboolean(因为该字段对于联合的所有成员都是公共的它将变成true|false,即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
}