typescript - 如何正确使用类型保护
我尝试使用用户定义的类型保护,但没有成功。也许有人可以告诉我如何应用我在这里试图实现的逻辑。
我有两个事件,并且相应地定义了DTO,然后我在它周围有一个包装器。
enum MyEvent {
Push = 'push',
Forward = 'forward',
}
class ForwardDTO {
email!: string;
subscriptionID!: string;
}
class PushDTO {
email!: string;
}
class EmitDTO {
payload!: ForwardDTO | PushDTO;
type!: MyEvent;
}
// Usage, I do convert this JSON into class instance with class-transformer but not showing it here to keep it simple
const dto: EmitDTO = JSON.parse('{"payload: {"email": "[email ", "subID": "aabbcc"}", "type": "forward"}');
if (dto.type === MyEvent.Forward) {
// Obviously not working the line below, I need to typecast
// const push = dto.payload.subID;
const push = (dto.payload as ForwardDTO).subID; // This works, but can we do without it?
}
我的目标是当我得到一个带有一个 if 语句的 EmitDTO 时,能够得到正确的类型。这可能吗?基本上,我是想在不进行类型转换的情况下得到正确的类型
我尝试了这种方法
class EmitDTO {
payload!: ForwardDTO | PushDTO;
type!: MyEvent;
isForward(): this.payload is ForwardDTO {
return this.type === MyEvent.Forward;
}
}
但是那是错误的,显然,类型保护不能这样使用。
答案#1
你可以将该类型保护签名修改为:
isForward(): this is { payload: ForwardDTO }
那么就不需要显式转换了:
if (dto.isForward()) {
const push = dto.payload.subID;
}
