我正在使用 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/