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. C/C++ 函数模板、全局变量、register、存储周期

    1.函数声明时可以简写,如: int max(int,int): 2.函数模板: 格式: template <typename haha>或template <class haha& ...

  2. Jmeter之定时器

    转自:https://www.cnblogs.com/imyalost/p/6004678.html 一.定时器的作用域 1.定时器是在每个sampler(采样器)之前执行的,而不是之后(无论定时器位 ...

  3. vue之loader处理静态资源

    webpack 是利用loader 来处理各种资源的,wepback的配置基本上就是为各种资源文件,指定不同类型的loader. 1,处理css 最基本的css 处理loader 是css-loade ...

  4. 16.04 下 ufw 防火墙的的开启、禁用、开放端口、关闭端口

    16.04 下的 ufw 防火墙相关操作使用ufw命令.通过ufw --help可以查看所有相关命令. 打开防火墙 sudo ufw enable 重启防火墙 sudo ufw reload 打开指定 ...

  5. hdfs深入:08、hdfs的JavaAPI以及如何解决winutils的问题

    /** * 通过url注册的方式访问hdfs,了解,不会用到 * @throws Exception */ 以下为详细代码://1.注册hdfs的url,让java代码能识别hdfs的url形式URL ...

  6. CocoaPods 命令和使用

    CocoaPods 命令 pod init 在新建的项目根目录下运行该命令,为当前项目新建podfile文件. pod install 下载和配置 podfile里定义的项目依赖(不包括已经下载和配置 ...

  7. install docker on centos7

    copy from:https://www.youtube.com/watch?v=pm55BUwQ0iE # Prerequisites - Kernel must be 3.10 at minim ...

  8. centos下安装redis(记录其中踩坑的过程)

    一.先下载到redis-3.0.4.tar.gz包(本文以3.0.4版本为例) 我将这个包放在/opt目录下,在/opt下并解压这个包 tar -zxvf redis-.tar.gz 然后进入redi ...

  9. python 连接sqlserver: pymssql

    停了一个月,终于还是把这个做了,工作需要!!!在装pymssql时,一直报错,确定了要先装freetds: 1. 安装freetds时报错,搜索到要先进行如下操作: brew unlink freet ...

  10. ExecutorService 线程池 (转发)

    1.ExecutorService java.util.concurrent.ExecutorService 接口.用来设置线程池并执行多线程任务.它有以下几个方法. Future<?> ...