[TypeScript] Collect Related Strings in a String Enum in TypeScript
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 = 412 } /**compiled code*/ (function (Port) { Port[Port["NUM"] = 412] = "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 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2017-09-14 [Vue + TS] Create your own Decorators in Vue with TypeScript
2017-09-14 [Vue + TS] Use Dependency Injection in Vue Using @Inject and @Provide Decorators with TypeScript
2017-09-14 [D3JS] Add more map layer and color
2017-09-14 [Javascript] Iterate Over Items with JavaScript's for-of Loop
2016-09-14 [Angular 2] More on *ngFor, @ContentChildren & QueryList<>
2016-09-14 [Angular 2] *ngFor
2016-09-14 [Angular 2] Directive intro and exportAs