简体   繁体   English

typescript中的const enum(tsc.js vs typescript.js)

[英]const enum in typescript (tsc.js vs typescript.js)

I have a const enum in typescript: 我在打字稿中有一个const enum

const enum LogLevel {
    TRACE = 0,
    DEBUG = 1,
    INFO = 2,
    WARN = 3,
    ERROR = 4,
    SILENT = 5
}

Based on the typescript spec the following field: 根据打字稿规范,以下字段:

private foo: number = LogLevel.DEBUG;

should be compiled as: 应编译为:

this.foo = 1 /* DEBUG */;

When I use tsc from the command line (Windows) it works as expected. 当我从命令行(Windows)使用tsc时,它按预期工作。 But when it is compiled with awesome-typescript-loader in a webpack project (which uses the typescript.js from node_modules as opposed to the tsc.js which is used by tsc), then the enum constant is not getting inlined: 但是当它在webpack项目中使用awesome-typescript-loader typescript awesome-typescript-loader编译时(使用来自node_modules的typescript.js而不是tsc使用的tsc.js),那么枚举常量不会被内联:

this.foo = LogLevel.DEBUG;

Both the tsc and the node module version are the same (2.0.2). tsc和节点模块版本都相同(2.0.2)。

I think there should not be a difference between the two. 我认为这两者之间不应该有区别。 Does anybody know why? 有人知道为什么吗?

Check your tsconfig.json file. 检查你的tsconfig.json文件。 If there is a setting with the name 'preserveConstEnums', set the value to 'false'. 如果存在名称为“preserveConstEnums”的设置,请将值设置为“false”。

I checked with the typescript 2.0.3 NPM-package and I can only see static numbers in my bundle.js. 我查看了typescript 2.0.3 NPM-package,我只能看到我的bundle.js中的静态数字。

It turned out it was caused by the declaration option in tsconfig.json. 事实证明它是由tsconfig.json中的declaration选项引起的。 If it is set to false, the two compilations produce the above inconsistent result. 如果设置为false,则两个编译会产生上述不一致的结果。 But when it is set to true, it works as expected. 但是当它设置为true时,它按预期工作。 Not sure why this flag has such an effect on the outcome. 不确定为什么这面旗帜会对结果产生这样的影响。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM