gpt4 book ai didi

typescript - 在 TypeScript 中切换特定类型

转载 作者:搜寻专家 更新时间:2023-10-30 20:55:15 26 4
gpt4 key购买 nike

我有一个接口(interface)Action:

interface Action {}

以及此Action SpecificAction 的实现:

class SpecificAction implements Action {
payload?: Any
}

是否可以在TS中构造一个switch操作符,像这样:

let action: Action
switch (action) {
case SpecificAction: //it works
console.log(action.payload) // it doesn't
}

在那种情况下是否有可能知道该操作已经是 SpecificAction 类型?

最佳答案

目前看来有一些选择,但都有一些缺点

  • 受歧视的工会 docs stackblitz ,但你需要一个专用属性作为鉴别器
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
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 , 但您暂时需要转换为所需的类型
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 - 在 TypeScript 中切换特定类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50774790/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com