0

Good afternoon!

I'm working on creating a function in TypeScript that receives a string | undefined array that returns another array containing only string elements. In other words, a function that matches this signature:

functionName(arraySource: (string | undefined)[]): string[]

I've tried filtering the array by its type (via functional programming) with a line like:

array.filter(x => typeof x === "string")

The problem here is the compiler: it says that the previous method returns a (string | undefined)[] variable (which cannot be assigned to a string[]).

Thanks in advance!

  • 1
    Does this answer your question? [TypeScript filter out nulls from an array](https://stackoverflow.com/questions/43118692/typescript-filter-out-nulls-from-an-array). The answer is applicable to your problem. – kelsny Sep 09 '22 at 23:30

1 Answers1

1

You can simply cast the result like this:

array.filter(x => typeof x === "string") as string[]

I'm not sure that there's a more sophisticated was to convince the compiler to recognized that the logical consequence of the filtering will be to remove undefined values.

kshetline
  • 12,547
  • 4
  • 37
  • 73
  • Thanks! Your answer is perfect and works fine, answer given in question referenced by @kelly with guards seems to work fine too and avoids casting – diego.guerrero Sep 10 '22 at 21:16