【问题标题】:TypeScript Property does not exist on type typeof enum, after checking that it definitely existsTypeScript 属性在 typeof 枚举类型上不存在,在检查它确实存在之后
【发布时间】: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

我已经通过创建PartialRecordAction 为键来解决它,但最好了解它为什么不适用于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


    【解决方案1】:

    您必须使用类型谓词。它看起来像这样:

    type Action =
    | 'WALK'
    | 'RUN'
    | 'SLEEP'
    | 'SWIM';
    
    enum Verbs {
      'WALK' = 'walking',
      'RUN' = 'running',
      'SWIM' = 'swimming',
    }
    
    const getVerb = (character: string, action: Action): string => {
      if (isVerb(action)) {
        const  verb = Verbs[action];
        return `${character} is ${verb}`;
      }
      return `${character} is doing something weird`;
    }
    
    // predicate here
    const isVerb = (action: Action): action is keyof typeof Verbs => {
      return action in Verbs; 
    }
    
    const character = 'Gom';
    const action: Action = 'RUN';
    const message = getVerb(character, action);
    console.log(message);
    

    TypeScript playground

    【讨论】:

      猜你喜欢
      • 2021-01-09
      • 2017-06-28
      • 2016-03-30
      • 2021-04-09
      • 1970-01-01
      • 1970-01-01
      • 2019-09-29
      • 2022-01-04
      • 2020-10-04
      相关资源
      最近更新 更多