【发布时间】:2021-05-06 15:10:45
【问题描述】:
在下面的例子中,一个角色可以执行几个动作,但是,我们只有一些动作的动词。
我们在返回之前检查动词是否存在。
TypeScript 不会接受动词存在,即使我们已经在 Enum 中检查了它。
type Action =
| 'WALK'
| 'RUN'
| 'SLEEP'
| 'SWIM';
enum Verbs {
'WALK' = 'walking',
'RUN' = 'running',
'SWIM' = 'swimming',
}
const getVerb = (character: string, action: Action): string => {
if (action in Verbs) {
// Property 'SLEEP' does not exist on type 'typeof Verbs'.ts(7053) ─┐
const verb = Verbs[action]; // <───────────────────────────────────┘
return `${character} is ${verb}`;
}
return `${character} is doing something weird`;
}
示例代码框: https://codesandbox.io/s/nostalgic-grass-7vrpt?file=/src/index.ts
我已经通过创建PartialRecord 以Action 为键来解决它,但最好了解它为什么不适用于Enum
const verbs: Partial<Record<Action, string>> = {
'WALK': 'walking',
'RUN': 'running',
'SWIM': 'swimming',
};
const getVerb = (character: string, action: Action): string => {
if (action in verbs) {
return `${character} is ${verbs[action]}`; // Works ????
}
return `${character} is doing something weird`;
};
【问题讨论】:
标签: typescript enums