0

How to get around this typescript error

export interface State {
    ids: number[] | string[];
}
const state: State = {ids: []};
state.ids.forEach(s => { }); // error here!!!

One way is that i take Ids separately in a variable and cast it and then loop through that variable

const ids = <string[]>state.ids;
ids.forEach(s => { });

But this is not looking very neat. Any way I can cast and loop in same line? something like

state.ids.forEach<string[]>(s => { }) // not working
3
  • 1
    (<string[]>state.ids).forEach(s => { }); would work as a one-liner Commented Nov 27, 2018 at 19:30
  • @UnholySheep Thanks - somehow I was confused and was trying :( <<string[]>state.ids>.forEach(s => { }); Thanks so much Commented Nov 27, 2018 at 19:34
  • (state.ids as string[]).forEach(s => { }); should also work Commented Nov 27, 2018 at 20:27

1 Answer 1

0

You will find this GitHub thread an interesting read. The issue is related to the inability to infer a common type between a union of arrays (in your case number[] and string[]). Since v3.3enter link description here, though, forEach can be called on a union of arrays, unless the --noImplicitAny flag is on (as the first arg of the callback will implicitly be typed as any).

So nowadays your issue can be solved without as casts, but still requires an explicit type annotation inside the callback:

type union = number[] | string[];

const i : union = [];
i.forEach((elem: number | string) => {
  //ok, do something
});

This is more faithful to your State type, as explicit casts are not safe. Having a union of arrays usually indicates that a generic would be more appropriate. Here is how you would change the interface to preserve the type-checking and avoid the initial problem altogether:

export interface State<I extends number | string>{
    ids: I[];
}
const state: State<string> = {ids: [1,2,3]}; //error

state.ids.forEach(s => { }); //ok if above is fixed

Also, see this Q&A about the same problem applied to map method.

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.