在 TypeScript 中切换特定类型 [英] Switch for specific type in TypeScript
本文介绍了在 TypeScript 中切换特定类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个接口Action
:
interface Action {}
以及这个Action
的实现SpecificAction
:
class SpecificAction implements Action {
payload?: Any
}
是否可以在 TS 中构造 switch 运算符,如下所示:
Is it possible in TS to construct a switch operator, like this:
let action: Action
switch (action) {
case SpecificAction: //it works
console.log(action.payload) // it doesn't
}
在这种情况下,是否有可能知道该操作已经属于 SpecificAction
类型?
Is it possible in that case to know, that action is already of SpecificAction
type?
推荐答案
目前看来有几个选项,但都有一些缺点
for the time being it looks like there are a few options, all of them with some drawbacks
- 歧视工会docs stackblitz,但您需要一个专用属性作为鉴别器
- discriminated unions docs stackblitz, but you'll need a dedicated property as discriminator
interface Action {}
class SpecificAction implements Action {
kind: "specific";
payload?: any;
}
class ToggleAction implements Action {
kind: "toggle";
toggle: boolean;
}
let action: SpecificAction | ToggleAction;
switch (action.kind) {
case "specific":
console.log(action.payload) // it works
break;
case "toggle":
console.log(action.toggle) // it works
break;
}
- 用户定义的类型保护 docs stackblitz,但你需要 if 语句而不是 switch
- User-Defined Type Guards docs stackblitz, but you'll need if statements instead of switch
interface Action {}
class SpecificAction implements Action {
payload?: any;
}
class ToggleAction implements Action {
toggle: boolean;
}
let isSpecific = (p: any): p is SpecificAction => !!p.payload
let isToggle = (p: any): p is ToggleAction => !!p.toggle
let action: Action;
if (isSpecific(action)) {
console.log(action.payload) // it works
} else if (isToggle(action)) {
console.log(action.toggle) // it works
}
- 构造函数属性 github stackblitz,但您需要暂时转换为所需的类型
- constructor property github stackblitz, but you'll need to cast to desired type for the time being
interface Action { }
class SpecificAction implements Action {
payload?: any;
}
class ToggleAction implements Action {
toggle: boolean;
}
switch (action.constructor) {
case SpecificAction:
console.log((<SpecificAction>action).payload) // it kinda works
break;
case ToggleAction:
console.log((<ToggleAction>action).toggle) // it kinda works
break;
}
这篇关于在 TypeScript 中切换特定类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文