1

I'm using Typescript ~2.4 if it matters.

I have a variable that is cast as {} | {}[] | string[]. I do a check when it's an array, and want to iterate over it. I figured a forEach is best on that:

(<{}[] | string[]>data).forEach((val) => {
    this.options.push(setupValue(val));
});

But it says Cannot invoke an expression whose type lacks a call signature. I can't see where I went wrong. I can't tell if this is a problem with how I'm using Typescript or my own logic?

3
  • 1
    Interestingly, both (<{}[]>data).forEach and (<string[]>data).forEach are fine. Commented Sep 25, 2017 at 4:07
  • So maybe it's a bug with Typescript? Or seems like intended behavior? Commented Sep 25, 2017 at 4:22
  • 1
    Looks buggy, to me, but others might know more about the specifics. Commented Sep 25, 2017 at 4:23

2 Answers 2

1

I think it's this issue: Can't call array methods on type (A[] | B[]) #18602

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

1 Comment

Thanks. Don't know how I missed that (I did check the bugs). Seems like it's something they're not going to address either...
1

You've got an array of empty objects ({}) or strings. If you accept to deal with an array of both, the TypeScript compiler lets you write :

(<({} | string)[]>data).forEach(val => {
    //...
});

1 Comment

Yah, this is the workaround that seems to work, though it's not an accurate representation of my typing.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.