【问题标题】:Flow - maybe type incompatible with union typesFlow - 可能类型与联合类型不兼容
【发布时间】:2017-06-13 20:18:52
【问题描述】:

流程码可以是run here.

使用流,我有一个函数,它接受一个键值对对象并为其获取一个值 - 它获取的值应该是字符串、数字或布尔值。

type ValueType =  string | number | bool | null | void;
type ObjectOfValues = {[string]: ValueType}
function getValueFromObjectOfValues(objectOfValues: ObjectOfValues, name: string): ValueType {
  return objectOfValues[name];
}

我定义了一些具有maybe 字符串属性的对象类型:

type SomeValueWithNullableString = {
  someProperty: ?string
}

然后我创建一个函数,它接受我的特定对象类型并调用该函数以从中获取值:

function getValue (someObject: SomeValueWithNullableString) {
  return getValueFromObjectOfValues(someObject, 'someProperty');
}

这会导致流程错误:

type ObjectOfValues = {[string]: ValueType} ^ 布尔值。此类型与 someProperty 的预期参数类型不兼容: ?string ^ 字符串 2:类型 ObjectOfValues = {[字符串]:值类型} ^ 号。此类型与预期的参数类型 9 不兼容:someProperty: ?string ^ 字符串

我做错了什么?

【问题讨论】:

    标签: javascript flowtype


    【解决方案1】:

    这段代码的问题是对象是可变的,所以getValueFromObjectOfValues可以合法地做objectOfValues.someProperty = 5

    如果 Flow 允许这种子类型关系,那么原来的调用者,他们认为他们有一个对象,someProperty 的类型为 ?string,现在将有一个对象,someProperty 的类型为 number,从而破坏了类型系统。

    要解决这个问题,你可以使用property variance。你需要像这样改变你的类型:

    type ObjectOfValues = {+[string]: ValueType}

    这意味着,粗略地说,如果你有一个ObjectOfValues 类型的对象,你只知道它的属性是ValueType 的某个子类型。这意味着当你从他们那里阅读时,你会得到一个ValueType。但是 Flow 不会让你给它们写信,因为它不知道它们实际上是什么类型——只是它们是 ValueType 的子类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-08
      • 2020-12-16
      • 2019-04-02
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      相关资源
      最近更新 更多