I am facing an issue in implementing TypeScript validation for filtering an array. I have a specific array of actions and I want to filter out internal actions from it. Despite my efforts, I am unable to properly communicate to TypeScript that the filteredActions array should not contain internalAction anymore.
Below is my attempted solution:
type ActionName = 'replaceText' | 'replaceImage' | 'internalAction';
interface Action {
name: ActionName
}
const INTERNAL_ACTIONS = ['internalAction'] as const;
type InternalActions = typeof INTERNAL_ACTIONS[number];
const actions: Action[] = [{
name: 'replaceText'
}, {
name: 'replaceImage'
}, {
name: 'internalAction'
}];
const isInternalAction = (name: ActionName): name is Exclude<ActionName, InternalActions> => name in INTERNAL_SLIDE_ACTIONS;
const filteredActions = actions.filter((action) => !isInternalAction(action.name));
for (const action of filteredActions) {
if (action.name === 'internalAction') {
// TypeScript error expected here because internalAction shouldn't be present
}
if (action.name === 'replaceImage') {
// No TypeScript error expected here
}
}