Skip to main content

Command Palette

Search for a command to run...

Get Enums (Enumerations) In Javascript | Using JS Doc

Published
L

Full stack web 3D developer

When I write javascript, I encounter a problem that there is no enum in javascript, and I accustomed to use enum to organise my code when write typescript. So I want to get a resolution to use enum in javascript.

What you can get:

  • Enum in javascript
  • Intellisense in IDE

What tsc do, when compile ts to js with enum.

//.ts
enum E1{
    A,B,C
}
//.js
var E1;
(function (E1) {
    E1[E1["A"] = 0] = "A";
    E1[E1["B"] = 1] = "B";
    E1[E1["C"] = 2] = "C";
})(E1 || (E1 = {}));

Define a function to generate enum like tsc

//generateEnum.mjs
export default function generateEnum(protoArr) {
    let _enum = {};
    for (let i = 0; i < protoArr.length; i++) {
        const _protoName = protoArr[i];
        const _cmdID = i;
        _enum[_enum[_protoName] = _cmdID] = _protoName;
    }
    return _enum;
}

Define a enum in d.ts

//type.d.ts
export interface ENUM_CMD_FN {
    ready_C2S,
    dealCards_S2C,
    competeForLandLordRole_C2S,
    playTurn,
    playCards_C2S,
    playCards_S2C,
    notAllowedByRule_S2C,
    gameEnd_S2
}

Import and define type in javascript

/**
 * @typedef {import("./type").ENUM_CMD_FN} ENUM_CMD_FN 
 */

Type and get your enum variable

import generateEnum from "./generateEnum.mjs"
/** 
 * @type ENUM_CMD_FN
 */
const ENUM_CMD_FN = generateEnum(
    [
        "ready_C2S",
        "dealCards_S2C",
        "competeForLandLordRole_C2S",
        "playTurn",
        "playCards_C2S",
        "playCards_S2C",
        "notAllowedByRule_S2C",
        "gameEnd_S2C"
    ]);

Then, the same as typescript.

enum-gif.gif

If you want to get the codes above, check the demo code .

Thanks for your reading.

Have a nice day.

More from this blog

如何将静态页面部署到Github Page,并绑定自定义域名

在仓库主页选择setting 点击pages 选择分支branch 输入自定义域名custom domain(设置好后点击save,系统将自动在项目根目录生成CNAME文件,文件内容为设置的当前域名) 在域名提供商处,添加DNS设置(以阿里云为例) 配置CNAME 配置IP,创建一个A类记录指向185.199.108.153 github将根据访问域名路由项目仓库(仓库名称为iddz.fun,并且根目录有CNAME文件) 最后,通过访问自定义域名,完成静态网站的部署...

Oct 4, 2023
如何将静态页面部署到Github Page,并绑定自定义域名

熟悉熟悉官方文档,逐步深入Babylon.js

文档的组织结构 通过前一篇文章的了解,我们会对Babylon.js有了一个大致的了解,整个文档主要是想带你逐步深入掌握这个Babylon.js所提供的所有内容。 内容主要分为一个概览和9个主要部分,这些部分包含章节,还有API详解和强大的文档和playground搜索功能。 - 1.Babylon.js特性 - Babylon.js是一个功能完备的游戏和渲染引擎,具有广泛的特性。这个部分将带你了解这些特性,并帮助你编码和使用它们。- 2.将Babylon.js添加到你的Web项目中 - 有多种...

Sep 25, 2023
熟悉熟悉官方文档,逐步深入Babylon.js

Lizhiyu's Blog

33 posts

Bringing the world closer together through play