【问题标题】:imported typescript enum doesn't work in compiled output导入的打字稿枚举在编译输出中不起作用
【发布时间】:2020-06-06 18:01:33
【问题描述】:

我正在尝试创建要在 index.ts 文件中使用的枚举集合。我不想将这些枚举直接保存在 index.ts 文件中,而是想从另一个文件中导入它们。

为此,我尝试在声明文件中声明命名空间:

declare namespace reservedWords {
  enum Variables {
    const = 'const',
    let = 'let',
    var = 'var',
  }
  ...
  // more enums and other things
}

export default reservedWords;

然后我尝试在 index.ts 文件中导入它:

import reservedWords from 'reservedWords.d.ts';

...

if (thing === reservedWords.Variables.const) doSomething();

在编译之前,我尝试将我的 src 目录添加到我的 typeroot 中,因为这是我保存 reservedWords.d.ts 文件的位置:

    "typeRoots" : ["./src", "./node_modules/@types"],

当我使用 tsc 编译 index.ts 文件时,我看到编译后的 index.js 文件说它正在导入 reservedWords,但 bin(导出)文件夹中不存在同名的文件。

import reservedWords from 'reservedWords';

如何让 index.ts 文件使用这些枚举?不确定使用命名空间的必要性,但我认为在声明文件中的命名空间内组织这些枚举是最好的做法。

【问题讨论】:

    标签: typescript enums typescript-typings


    【解决方案1】:

    你需要exportenums

    declare namespace reservedWords {
      export enum Variables {
        const = 'const',
        let = 'let',
        var = 'var',
      }
      ...
      // more enums and other things
    }
    
    export default reservedWords;
    

    index.ts

        import * as reservedWords from 'reservedWords'
    

    【讨论】:

    • 如何在 index.ts 中像这样使用Variables
    • reservedWords.Variables.const
    【解决方案2】:

    您可能正在寻找常量枚举。此打字稿功能将帮助您在请求的位置生成枚举值。这是您的案例的示例:

    const enum Variables {
      const = 'const',
      let = 'let',
      var = 'var',
    }
    

    更多详情请见official documentation

    P.S.:我想没有必要使用import reservedWords from 'reservedWords.d.ts';,因为您已经指定了类型类型根。

    【讨论】:

      猜你喜欢
      • 2015-03-01
      • 2019-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-29
      • 2016-07-13
      • 2016-11-21
      • 1970-01-01
      相关资源
      最近更新 更多