Home > Software design >  Using .forEach() after checking if variable is Array type
Using .forEach() after checking if variable is Array type

Time:02-12

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?

CodePudding user response:

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

  • Related