一个函数是否可以在它通过时自动转换一个对象

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

假设我有一个对象,在

这样的场景中可以是两个不同的 classes
const obj: A | B = ...
        
if ( isClassA(obj) ) {
    // obj = <A> obj
    ...
} else {
    // obj = <B> obj
    ...
}

有没有办法根据 isClassA() 的结果自动将 obj 转换为适当的 class?

您在寻找 Type Predicate 吗?

Example on Playground

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