1

I have a line of code that grabs the value from an array of selected options (each option contains a value and label). value will never be undefined:

let marketplaces: string[] = selectedMarketplaces.map(m => m.value) 

Instead I get error because typescript treats it as a union of string and undefined:

Argument of type '(string | undefined)[]' is not assignable to parameter of type 'string[]'.

To try to workaround, I tried to explicitly filter undefined

let marketplaces: string[] = selectedMarketplaces.map(m => m.value).filter(v => v !== undefined);

But still got the same error message. How do I work around this?

Jay Hu
  • 83
  • 7
  • TS doesn't understand that a callback of the form `v => v !== undefined` has any implication for narrowing the type of a value passed to it; you need to explicitly annotate it as a type guard function like `(v): v is string => v !==undefined`, as shown [here](https://tsplay.dev/W48P7W), if you want that kind of behavior. – jcalz Jan 28 '22 at 21:17

0 Answers0