gpt4 book ai didi

javascript - 流 - 类型可能与联合类型不兼容

转载 作者:行者123 更新时间:2023-12-03 04:06:26 27 4
gpt4 key购买 nike

流程代码可以是run here.

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

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} ^ boolean. This type is incompatible with the expected param type of someProperty: ?string ^ string 2: type ObjectOfValues = {[string]: ValueType} ^ number. This type is incompatible with the expected param type of 9: someProperty: ?string ^ string

我做错了什么?

最佳答案

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

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

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

type ObjectOfValues = {+[string]: ValueType}

这意味着,宽松地,如果您有一个 ObjectOfValues 类型的对象,您所知道的是它的属性是 ValueType 的某些子类型。这意味着当您阅读它们时,您将得到 ValueType 。但是 Flow 不会让你写信给它们,因为它不知道它们实际上是什么类型——只是知道它们是 ValueType 的子类型。 .

关于javascript - 流 - 类型可能与联合类型不兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44530777/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com