问题描述
我在流程中遇到了一个奇怪的错误.我只是想拥有一个接受具有 amount
属性的对象数组的函数,但是在为对象提供更多属性时出现错误.
I am having a strange error with flow.I'm simply trying to have a function that accepts an array of objects with an amount
property but I'm having errors when providing objects with more properties.
const sum = (items: Array<{amount: number}>) => {/* something */}
type Item = {
amount: number,
name: string
};
const list: Array<Item> = [];
sum(list);
这给了我以下错误:
10: const list: Array<Item> = [];
^ property `name`. Property not found in
2: const sum = (items: Array<{amount: number}>) => {/* something */}
^ object type
推荐答案
类似于此处描述的问题: https://github.com/facebook/flow/issues/1644
Similar to the issue described here: https://github.com/facebook/flow/issues/1644
这是不允许的,因为您有声明
This is not allowed, because the declaration you have,
const sum = (items: Array<{amount: number}>) => {/* something */}
将允许
const sum = (items: Array<{amount: number}>) => {
items.push({amount: 4});
};
在给出 items
声明的情况下完全有效.传递给 sum
的数组是您 Item
类型的列表,该列表需要一个 name
,此处未设置.
which is totally valid given the declaration of items
. The array passed to sum
is a list of your Item
type, which requires a name
, which isn't set here.
如前所述, $ ReadOnlyArray
可以工作,因为它是只读的,不能再添加任何项目.或者,您可以将类型定义从 sum
完全删除,让Flow推断它们,或者将 Array< {amount:number}>
更改为 Array&*; *.
,因此Flow知道它是一个数组,但是会推断内容的类型.(您在评论中留下的)另一种选择是
As you mentioned, $ReadOnlyArray
works, because it is read-only and can't have more items added to it. Alternatively you could drop the type definitions from sum
entirely and let Flow infer them, or change Array<{amount: number}>
to Array<*>
so Flow knows it is an array, but will infer the type of the content. Another alternative (that you left in the comments) is
const sum = <T : {amount: number}>(items: Array<T>) => {/* something */}
这将根据您对 sum(list)
的调用将 T
设置为 Item
,但限制是它将接受任何> T
是具有数字 amount
属性的对象.
which will set T
to Item
based on your call to sum(list)
, with the restriction that it will accept any T
that is an object with a numeric amount
property.
这可能是最好的选择.
这篇关于对象类型的Flowtype数组不允许额外的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!