As of TypeScript 2.4, it is now possible to define string enums, or more precisely, enums with string members. Just like any other numeric enum, string enums can be made constant using the const modifier so that they disappear entirely from the generated JavaScript; in this case, all enum values will be inlined into the output.

For example,we  have the code:

fetch("https://swapi.co/api/people/1/", {
headers: {
Accept: 'application/json'
}
})
.then((res) => res.json())
.then(response => {
console.log(response.name)
});

We want to replace 'application/json' to use Typescript enum.

enum MediaTypes {
JSON = "application/json"
} fetch("https://swapi.co/api/people/1/", {
headers: {
Accept: MediaTypes.JSON
}
})
.then((res) => res.json())
.then(response => {
console.log(response.name)
});

From the compiled code, we can see the output:

var MediaTypes;
(function (MediaTypes) {
MediaTypes["JSON"] = "application/json";
})(MediaTypes || (MediaTypes = {}));
fetch("https://swapi.co/api/people/1/", {
headers: {
Accept: MediaTypes.JSON
}
})
.then(function (res) { return res.json(); })
.then(function (response) {
console.log(response.name);
});

The compile code, it add a IIFE define and set JSON code to 'application/json'.

Sometime, we don't want this meta code goes into production code, the way to do this is add "const":

const enum MediaTypes {
JSON = "application/json"
}
/*compiled code**/ fetch("https://swapi.co/api/people/1/", {
headers: {
Accept: "application/json" /* JSON */
}
})
.then(function (res) { return res.json(); })
.then(function (response) {
console.log(response.name);
});

As we can see, the output code doesn't have IIFE anymore, the code is much smaller.

You can get reverse mapping by using number:

enum Port {
NUM =
} /**compiled code*/
(function (Port) {
Port[Port["NUM"] = ] = "NUM";
})(Port || (Port = {}));

Last thing, if you really want to use "const" keyword but still want to keep IIFE meta code, you can set up in tsconfig.json:

{
"preserveConstEnums": true
}

[TypeScript] Collect Related Strings in a String Enum in TypeScript的更多相关文章

  1. strings.h 与 string.h 头文件的区别

    今天使用 man string 来查看 string 文件的使用的方法(毕竟里面的函数名字和传入参数和发挥参数的类型,如果一段时间不使用,会产生遗忘.) 偶然发现,string.h 的man page ...

  2. POJ 3096 Surprising Strings(STL map string set vector)

    题目:http://poj.org/problem?id=3096 题意:给定一个字符串S,从中找出所有有两个字符组成的子串,每当组成子串的字符之间隔着n字符时,如果没有相同的子串出现,则输出 &qu ...

  3. [TypeScript] Query Properties with keyof and Lookup Types in TypeScript

    The keyof operator produces a union type of all known, public property names of a given type. You ca ...

  4. [VueJS + Typescript] Decouple Dependencies Using IoC Containers in Vue with TypeScript and InversifyJS

    Using Object Oriented Programming, OOP, style allows us to apply Inversion of Control, IoC, and more ...

  5. 深入浅出TypeScript(5)- 在React项目中使用TypeScript

    前言 在第二小节中,我们讨论了利用TypeScript创建Web项目的实现,在本下节,我们讨论一下如何结合React创建一个具备TypeScript类型的应用项目. 准备 Webpack配置在第二小节 ...

  6. [TypeScript] Dynamically Allocate Function Types with Conditional Types in TypeScript

    Conditional types take generics one step further and allow you to test for a specific condition, bas ...

  7. [TypeScript] Find the repeated item in an array using TypeScript

    Say you have an array that has at least one item repeated. How would you find the repeated item. Thi ...

  8. TypeScript enum 枚举实现原理

    TypeScript enum 枚举实现原理 反向映射 https://www.typescriptlang.org/docs/handbook/enums.html enum Direction { ...

  9. enum和int、string的转换操作

    enum Countries{    中国 = 5,    美国,    俄罗斯,    英国,    法国} enum 和 int enum -> intint num = (int)Coun ...

随机推荐

  1. java调用jacob生成pdf,word,excel横向

    /* * 传进一个office文件的byte[]以及后缀,生成一个pdf文件的byte[] */ public byte[] jacob_Office2Pdf(byte[] srcFileBytes, ...

  2. matlab中数据类型

    在MATLAB中有15种基本数据类型,分别是8种整型数据.单精度浮点型.双精度浮点型.逻辑型.字符串型.单元数组.结构体类型和函数句柄.这15种基本数据类型具体如下. 有符号整数型:int8,int1 ...

  3. Ajax请求WebService跨域问题

    1.背景 用Jquery中Ajax方式在asp.net开发环境中WebService接口的调用 2.出现的问题 原因分析:浏览器同源策略的影响(即JavaScript或Cookie只能访问同域下的内容 ...

  4. windows sdk编程为应用程序添加图标

    #include <windows.h> /*消息处理函数声明*/ HRESULT CALLBACK WindowProc(HWND hwnd, UINT message, WPARAM ...

  5. 使用JQuery MiniUI,json数据构建TreeGrid(树图)

    index.html直接上代码. 需要引用MiniUI的boot.js <!DOCTYPE html> <html> <head> <meta charset ...

  6. redis新特性

    摘自<redis 4.xcookbook> 从实例重启同步] 故障切换同步] 4.0之前从实例主键过期bug redis4新特性 Memory Command Lazy Free PSYN ...

  7. C#导出word [无规则表结构+模板遇到的坑]

    1)当然可以考虑使用aspose.word.使用书签替换的方案替换模板中对应的书签值. 2)但是我使用了Interop.Word,下面记录使用类及要注意的地方 3)使用类 Report.cs 来自于网 ...

  8. HDOJ 1846 Brave Game - 博弈入门

    题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=1846 经典基础博弈,首先面对(m+1)的人一定会输,依次往后推即可: #include<iost ...

  9. Codeforces450 B. Jzzhu and Sequences

    B. Jzzhu and Sequences time limit per test 1 second memory limit per test 256 megabytes input standa ...

  10. 绑定IP 绑定设备

    首先引别人的组播测试如下 1. 一个udp client可以同时往多个组播地址发送数据,多个udpclient可以同时往一个组播发数据. 2. 本地udp必须监听组播端口,否则收不到数据.3. 一个u ...