Starfish
Starfish

Reputation: 3574

Using .forEach() after checking if variable is Array type

I have a generic functional component in which I got the following code:

if(Array.isArray(entry[key as keyof T]) {
    entry[key as keyof T].forEach((item: T) => { ... });
}

Where key is a variable string. The .forEach is red underlined with the following error message:

Property 'forEach' does not exist on type 'T[keyof T]'

even though I checked if the value is an array in the conditional statement. How do I work around this?

Upvotes: 0

Views: 51

Answers (1)

Marces Engel
Marces Engel

Reputation: 784

I'd suggest making it a bit easier for TS:

const value = entry[key as keyof T]
if (Array.isArray(value)) {
  value.forEach((item: T) => {});
}

Edit: Is your entry some kind of recursive structure? Otherwise the typing looks a little odd. Maybe you'd like to share a little bit more of your code/intention.

Edit 2: Playground sample https://www.typescriptlang.org/play?#code/DwFQBApgHgLhB2ATAzmA3gXwHwAoEwCcBPALjBAEowBeLdAKDDAGMB7eZGMAawiJrAByQfUYt2nMADcAhgBsArhAH5iAbV78ZqTawBm5ALpiAlgZwBBAgRlEAdCeRWbRHLMUQKVNGKbuldnqsBACiMswAFjg4JnAAtmSUNHSYFADcYhj0WUA

Upvotes: 3

Related Questions