无法传播对象文字,因为 Flow 无法确定对象文字的类型
Cannot spread object literal because Flow cannot determine a type for object literal
以下(简化)代码
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 对象没有 属性.
的布尔值
有两种可能的修复方法:
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
以下(简化)代码
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 containisSelected
with a type that conflicts withisSelected
's definition in object literal [1]. Try makingCategory
[2] exact.
我错过了什么?
您的类别类型不准确,这意味着它可能包含您的类型中未定义的属性。出现错误是因为如果 c 包含一个名为 isSelected
的 属性,它可能会导致 Option 对象没有 属性.
有两种可能的修复方法:
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