gpt4 book ai didi

javascript - 无法传播对象文字,因为 Flow 无法确定对象文字的类型

转载 作者:行者123 更新时间:2023-12-05 00:56:36 24 4
gpt4 key购买 nike

以下(简化)代码

type Category = {
id: string,
name: string,
};

type Option = {
id: string,
name: string,
isSelected: boolean,
};

const options = categories.map((c: Category): Option => ({
isSelected: true,
...c,
}));

产生错误:

Flow: Cannot spread object literal because Flow cannot determine a type for object literal [1]. Category [2] is inexact, so it may contain isSelected with a type that conflicts with isSelected's definition in object literal [1]. Try making Category [2] exact.

我错过了什么?

最佳答案

您的类别类型不准确,这意味着它可能包含未在您的类型中定义的属性。出现错误是因为如果 c 包含名为 isSelected 的属性,则可能导致 Option 对象没有该属性的 bool 值。

有两种可能的修复方法:

const options = categories.map((c: Category): Option => ({
...c,
isSelected: true,
}));

这将导致 isSelected: true 总是优先于 c.isSelected(如果它曾经存在的话)。

第二个修复是使类别准确。

type Category = {|
id: string,
name: string,
|};

这样做将禁止它拥有额外的属性。您应该尽可能使您的对象精确。

更多信息,您可以阅读https://flow.org/en/docs/types/objects/#toc-exact-object-types

关于javascript - 无法传播对象文字,因为 Flow 无法确定对象文字的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62286574/

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