'Narrow generic to specific interface when filtering array

EDIT: Here is a minimal reproducible example.

I have a set of subclasses (defined as interfaces A, B for sake of example) which all extend Base. I have defined a list of rules that can act on any of those subclasses based on _className which is defined on Base.

I'm filtering the list of rules based on _className so that only relevant rules will be processed for a given editor input - however, I'm unable to figure out how (or if it's reasonably possible) for rule.test(editor) to know that it now is a single subclass (A or B).

Right now, I'm getting the common Type 'A' is missing the following properties from type 'B': content, tabs - ts(2345) error.

    validate(editor: A | B) { // How do I type this to let test understand it's editor type based on _className?
        const ruleResults = this.rules.filter(rule => rule.editorCompatibility.includes(editor._className)).flatMap(rule => {
            const result = rule.test(editor)?.filter(this.isRuleResultTypeGuard)
            if (result) {
                return {
                    result: result,
                    summary: rule.summarize(result)
                }
            } else {
                return [] // FlatMap automatically filters empty arrays values
            }
        })
    ...
    }

I've tried user-defined type guards but didn't make much progress as they seem to be able to only identify a single type, rather than from a set of types.

Any direction would be most appreciated. Thanks!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source