Typescript 如何将字符串转换为枚举和类型?
这个问题可能看起来很相似,但我的情况有点复杂。我有两个不同的枚举和另一个总和类型:Typescript 如何将字符串转换为枚举和类型?,typescript,enums,Typescript,Enums,这个问题可能看起来很相似,但我的情况有点复杂。我有两个不同的枚举和另一个总和类型: enum InteractiveStep { Pick = 'PICK', Ban = 'BAN' } enum AutoStep { RandomPick = 'RANDOM_PICK', LastPick = 'LAST_PICK' } type ActionStep = InteractiveStep | AutoStep 如何检查ActionStep类型中是否包含任意
enum InteractiveStep {
Pick = 'PICK',
Ban = 'BAN'
}
enum AutoStep {
RandomPick = 'RANDOM_PICK',
LastPick = 'LAST_PICK'
}
type ActionStep = InteractiveStep | AutoStep
如何检查ActionStep
类型中是否包含任意字符串,并安全地将其转换?使用,我可以得出以下结论:
enum InteractiveStep {
Pick = 'PICK',
Ban = 'BAN'
}
enum AutoStep {
RandomPick = 'RANDOM_PICK',
LastPick = 'LAST_PICK'
}
type ActionStep = InteractiveStep | AutoStep
const ActionStep = {...InteractiveStep, ...AutoStep}
const inputString: string = 'RANDOM_PICK'
const inputStep: ActionStep = ActionStep[inputString as keyof typeof ActionStep];
通过使用,我能够得出以下结论:
enum InteractiveStep {
Pick = 'PICK',
Ban = 'BAN'
}
enum AutoStep {
RandomPick = 'RANDOM_PICK',
LastPick = 'LAST_PICK'
}
type ActionStep = InteractiveStep | AutoStep
const ActionStep = {...InteractiveStep, ...AutoStep}
const inputString: string = 'RANDOM_PICK'
const inputStep: ActionStep = ActionStep[inputString as keyof typeof ActionStep];