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

1 Answer 1

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.

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

1 Comment

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

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.