Here's a handy function that always returns an array of strings:
(arr: (string | undefined)[]): string[] => arr.filter(item => item !== undefined);
However, TypeScript may not compile this code as expected due to its inference issues with the filter predicate. Even explicitly typing the predicate does not seem to resolve the issue:
const predicate = (item: string | undefined): item is string => item !== undefined;
(arr: (string | undefined)[]): string[] => arr.filter(item => predicate(item));
See the modified version in the playground
Another alternative approach involves using a more verbose method, which might potentially be slower:
(arr: (string | undefined)[]): string[] => {
const ret: string[] = [];
for (const item of arr) {
if (item !== undefined) {
ret.push(item);
}
}
return ret;
}
Try out this alternative on the playground
Are there any experimental flags that can be enabled in tsconfig.json
to assist TypeScript in making type inferences based on the filter predicate?