Array of object type Flowtype does not allow adding additional properties

I have a strange error with a stream. I'm just trying to get a function that takes an array of objects with a property amount

, but I'm getting errors when providing objects with a lot of properties.

const sum = (items: Array<{amount: number}>) => {/* something */}

type Item = {
  amount: number,
  name: string
};

const list: Array<Item> = [];

sum(list);

      

This gives me the following errors:

10: const list: Array<Item> = [];
                      ^ property `name`. Property not found in
2: const sum = (items: Array<{amount: number}>) => {/* something */}
                             ^ object type

      

https://flow.org/try/#0FAYw9gdgzgLgBFArgWzgXjgCgJYwKbJQBccAggE7kCGAngDwDeVyYiEMJEKARnuQL4A+AJTpBcBgHoAVAjDI8MABbYIAczjTJ-YLpg0ADnjgBJfKgwNgcOM1btOPPgBprcCMzwlY5VWuD8ANy64NDwADbYsCQU1PRmBOIYANoAusHASMiYkbDCgUA

+3


source to share


1 answer


Similar to the issue described here: https://github.com/facebook/flow/issues/1644

This is not valid because the ad you have is

const sum = (items: Array<{amount: number}>) => {/* something */}

      

will allow

const sum = (items: Array<{amount: number}>) => {
    items.push({amount: 4});
};

      



which is quite true when declaring items

. The array passed to sum

is a list of your type Item

that is required name

, which is not listed here.

As you mentioned, it $ReadOnlyArray

works because it is read-only and cannot have any more items added. Alternatively, you can completely remove the type declarations from sum

and let Flow infer them, or change them Array<{amount: number}>

to Array<*>

so that Flow knows it's an array, but infers the content type. Another option (which you left in the comments):

const sum = <T : {amount: number}>(items: Array<T>) => {/* something */}

      

which will set T

in Item

based on your sum(list)

constraint call that it will accept anyone T

that is an object with a numeric property amount

.

This is probably the best option.

+5


source







All Articles