1

I am using typescript in a React project and iterating through an array of objects to return components.

I am getting the expected result in the application with no errors in the console, but in VSCode I am getting this error: Property 'amount' does not exist on type 'object'. For every property that I am referencing in the map.

Here is the code snippet:

{recentHistory.map((item) => {
    if (item.type === 'ADD') {
        return <AddItem amount={item.amount} memo={item.memo} />
    } else if (item.type === 'SUBTRACT') {
        return <SubtractItem amount={item.amount} memo={item.memo} />
    }
})}

And a screenshot in VSCode.

VSCode snippet

Again this is producing the expected output and works great, VSCode is just throwing these warnings.

1 Answers1

1

Define an interface for item of the form

interface Item {
  amount: number;
  memo: string;
  type: string;
}

Now, recentHistory is of type object array, you might have a code like this somewhere:

let recentHistory = [];

You need to change the declaration to hold array of type Item:

let recentHistory: Array<Item> = [];

credits: Linda Paiste

  • "Define an interface" is correct. Assigning the type inside a callback is a bandaid solution to a problem that should be fixed higher up (in code that we haven't seen). The `recentHistory` array should to be typed as `Item[]`. It if is then the `item` will get type `Item` automatically. – Linda Paiste Mar 22 '21 at 18:58
  • Aah...I should not have answered so quickly. I'll edit it – Flemin Adambukulam Mar 22 '21 at 19:04