reactjs - 为什么 Typescript 认为我的枚举未定义?

标签 reactjs typescript enums redux

我正在使用 Typescript、Redux 和 React,所有这些对我来说都是新的,所以这可能有一个我只是没有看到的简单修复。

我有一个 actions.ts 文件,其中包含这样的枚举:

export enum AnimalTypes {
    CAT = 'CAT',
    DOG = 'DOG'
}

我将它导入到我的 reducers.ts 文件中,并试图在这样的日志语句中使用它:

import {AnimalTypes} from './actions';

export function someFunction() {
    // Print the word "CAT"
    console.log(AnimalTypes[AnimalTypes.CAT]);
}

当我尝试启动我的网站时出现以下错误:

TypeError: Cannot read property 'CAT' of undefined
  at someFunction (reducer.ts:5)
  at combineReducers.js:20
  etc.

我的 IDE 没有给我任何错误,TSLint 也没有。我在网上阅读了很多试图找到答案的文章,但我最接近的答案来自于他们的枚举中没有“导出”关键字的人,而我有。

这里可能发生了什么?如果有任何帮助,我将不胜感激。

谢谢。

编辑: 这不是它有问题的反向映射,而是枚举的任何用法。那只是我能想到的最短的用法。我实际上是在 switch 语句中使用它:

import {AnimalTypes} from './actions';

export function otherFunction(animal) {
    switch (animal.type) {
        case AnimalTypes.CAT:
            // Do stuff
}

当我构建上面的代码时,我得到了这个错误Uncaught TypeError: Cannot read property 'CAT' of undefined

最佳答案

typescript 的这个特性被称为“反向映射”,根据文档,它只支持数字枚举。这是来自 https://www.typescriptlang.org/docs/handbook/enums.html 的片段:

In addition to creating an object with property names for members, numeric enums members also get a reverse mapping from enum values to enum names.

关于reactjs - 为什么 Typescript 认为我的枚举未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50183529/

相关文章:

enums - 在 Rust 中使用枚举实现动态多态

javascript - 如何在TypeScript定义中定义ReactFunctionalComponent的返回类型

Angular 拖放,事件中的空文件数组

reactjs - 类型 'Element[]' 缺少类型 'Element' : type, props、key 中的以下属性

C#:获取枚举名称作为字符串

enums - "cannot infer an appropriate lifetime"当使用闭包返回对枚举变体内容的引用时

html - 居中对齐的word文档样式输入标签

javascript - 如何使用 FileUpload 向受 Azure AD 保护的 REST API 发出 REST API 发布请求

android - 我可以将 material-components-android 与 React-Native 一起使用吗?

typescript - 如何将 Vue 插件包含到 Vue TypeScript 的模板中?