我不知道如何有效地使用工会类型的警卫。我试图对我的一些类方法使用联合类型,以便如果它们正常执行,则返回一个期望值,但如果失败,则返回一个自定义通知器对象。就像这样:
考虑一下这个例子:
class OpError {
message : string;
constructor(msg : string) {
this.message = msg;
}
}
class Foo {
name: string;
}
class Bar {
getFooName(myFoo : Foo) : string | OpError {
if (!myFoo.name) {
return new OpError("You forgot to name the Foo.")
} else {
return myFoo.name;
}
}
}
let myFoo = new Foo();
let myBar = new Bar();
let result = myBar.getFooName(myFoo);
if (typeof result === 'object') {
console.log(result.message)
} else {
console.log(result);
}虽然说: string | OpError {的语法非常有用和优雅,但是类型守卫‘the of result === ' object ')看起来很笨拙,里面有一根神奇的字符串,如果“普通”返回值也是一个对象而不是原语,则无法工作。
看来一定有更好的办法,但不知道那可能是什么。
https://stackoverflow.com/questions/72720476
复制相似问题