运行时未定义枚举类型

2024-01-11

我遇到一个问题,Typescript 编译器成功编译了我的代码,但运行时却给出了未定义的类型错误。

在我的应用程序中我创建了一个types.ts文件,其中一些内容在多个其他 ts 文件之间共享。它包含一个字符串枚举,例如:

enum MyEnum {
  One = "one";
  Two = "two";
}

当我这样定义它时。编译器允许我在其他 ts 文件中使用它,并且看起来很高兴。但是,在运行时我收到错误“MyEnum 未定义”。

我知道有两种方法可以解决这个问题:

  1. 在使用它的文件中定义枚举。但我认为这不会为其他想要使用它的文件解决任何问题。
  2. 在 types.ts 文件中使用“export”,并在使用每个类型的地方显式导入该类型。

我对 Typescript 还很陌生,我觉得我可能误解了一些基本的东西。

首先,我不明白为什么 Typescript 编译器会在出现运行时错误时愉快地编译我的代码。如果我使用过的话我就会理解declare关键字,告诉编译器有些东西should在运行时可用,但在这种情况下,我不明白为什么它应该假设枚举来自 types.ts 文件以外的任何地方。

其次,我想在我的应用程序中全局定义类型,并让它们在任何地方都可用,而不必每次使用它们时都导入它们。我该如何实现这个目标?或者这可能被认为是不好的做法?

我正在使用 Typescript 2.6,我的配置如下所示:

{
  "compilerOptions": {
    /* Basic Options */
    "target": "es6",
    "module": "commonjs",
    "lib": ["es6", "es7", "esnext"],

    "sourceMap": true /* Generates corresponding '.map' file. */,
    "outDir": "build" /* Redirect output structure to the directory. */,
    "removeComments": true /* Do not emit comments to output. */,

    /* Strict Type-Checking Options */
    "strict": true /* Enable all strict type-checking options. */,

    /* Additional Checks */
    "noUnusedLocals": true /* Report errors on unused locals. */,
    "noUnusedParameters": true /* Report errors on unused parameters. */,
    "noImplicitReturns": true /* Report error when not all code paths in function return a value. */,
    "noFallthroughCasesInSwitch": true /* Report errors for fallthrough cases in switch statement. */,

    "plugins": [{ "name": "tslint-language-service" }],
    "skipLibCheck": true // because firebase-sdk has wrong type files now (Nov 18)
  },
  "include": ["src/**/*"],
  "exclude": ["build"]
}

就我而言undefinedenum,结果发现这是因为循环导入:

export enum A {...}文件中定义a.ts, export const b = ...文件中定义b.ts;

import {A} from './a.ts' in b.ts, while import {b} from './b.ts' in a.ts.

删除循环导入后错误消失。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

运行时未定义枚举类型 的相关文章

随机推荐