網站搜尋

TypeScript - Enum 類型在運行時未定義


我遇到一個問題,Typescript 編譯器可以成功編譯我的程式碼,但在執行時卻給我未定義類型的錯誤。

在我的應用程式中,我建立了一個 types.ts 檔案,裡面包含一些在多個其他 ts 檔案之間共享的內容。它包含一個像這樣的字串列舉:

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

當我這樣定義它時,編譯器允許我在其他 ts 檔案中使用它,並且似乎沒有問題。然而,在執行時我收到錯誤“MyEnum 未定義”。

我知道有兩種方法可以解決這個問題:

  1. 在使用該枚舉的文件中定義它。但我認為這並不能解決其他想要使用它的文件的問題。
  2. 在 types.ts 文件中使用 "export",並在每個使用到的地方明確導入每個類型。

我對 Typescript 還相當陌生,而且我覺得我可能誤解了一些基本概念。

首先,我不明白為什麼如果會發生運行時錯誤,TypeScript 編譯器還會高高興興地編譯我的程式碼。如果我使用了 declare 關鍵字,告訴編譯器某些東西在運行時 應該 可用,那我還能理解,但在這種情況下,我不明白為什麼它會假設這個 enum 會來自 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"]
}

答案#1

在我遇到的 undefined 列舉案例中,結果發現是因為循環導入所致:

在檔案 a.ts 中定義了 export enum A {...},在檔案 b.ts 中定義了 export const b=...;

在 b.ts 中使用 import {A} from './a.ts',而在 a.ts 中使用 import {b} from './b.ts'。

在移除循環匯入後,錯誤消失了。

答案#2

你還有另一種方法可以做到這一點。如果你不想導出你的枚舉,你可以將它定義為 const enum

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

這些會被編譯器內聯,並在編譯過程中完全移除。

答案#3

當我導入再導出的枚舉時,我遇到了同樣的問題。它導致了運行時錯誤。

布局.ts

export enum Part { Column, Row }

index.ts

export * from './layout'

元件.ts

import { Part } from '../entities' // This causes error
import { Part } from '../entities/layout' // This works

答案#4

我之所以有這個問題,是因為我使用了 declare 在

export declare enum SomeEnum

而不是

export enum SomeEnum