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!
CodePudding user response:
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.