I have some code that filters an array with type (Suggestion|undefined)[]
into an array with type Suggestion[]
, but I feel it does so very inelegantly:
const optionsProvider: AutocompletionProvider = () => {
const results: (Suggestion|undefined)[] = flagDescriptions.map(descriptions => {
let shortFlagWithArgument = descriptions[0].match(/^ *-(\w) (\w*)$/);
let shortFlagWithoutArgument = descriptions[0].match(/^ *-(\w) *(.*)$/);
if (shortFlagWithArgument) {
const flag = shortFlagWithArgument[1];
const argument = shortFlagWithArgument[2];
const description = combineManPageLines(descriptions.slice(1));
return new Suggestion({
value: `-${flag}`,
style: styles.option,
description,
displayValue: `-${flag} ${argument}`,
});
} else if (shortFlagWithoutArgument) {
const flag = shortFlagWithoutArgument[1];
const description = combineManPageLines([shortFlagWithoutArgument[2], ...descriptions.slice(1)]);
return new Suggestion({
value: `-${flag}`,
style: styles.option,
description,
});
}
});
const filteredResults: Suggestion[] = [];
results.forEach(result => {
if (result) {
filteredResults.push(result);
}
});
return filteredResults;
};
In straight JS, this would just be array.filter(element => element !== undefined)
but the best working solution I could come up with in TypeScript was to push
the defined elements into a separate array within a forEach
.
For context:
type AutocompletionProvider = (context: AutocompletionContext) => Suggestion[] | Promise<Suggestion[]>;
Original PR: https://github.com/shockone/black-screen/pull/623/files
(Suggestion|undefined)[]
in the first place. It is ok to putundefined
into aSuggestion[]
, so why not change the type to be simplySuggestion[]
throughout? \$\endgroup\$