0

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?

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.