Is it possible for a function to automatically cast an object if it passes

Suppose I have an object that can be two different classes in a scenario like

const obj: A | B = ...
        
if ( isClassA(obj) ) {
    // obj = <A> obj
    ...
} else {
    // obj = <B> obj
    ...
}

Is there a way to automactically cast obj to its appropriate class based on the result of isClassA()?

Answer

Are you looking for a Type Predicate?

Example on Playground

function isClassA(obj: any): obj is A {
    return /* your implementation */;
}