javascript - 如何在 typescript 中使用 bigint 初始值设定项创建类似枚举的对象?

标签 javascript typescript

我理想的做法是:

enum Distance {
    Far: 0n,
    Medium, // 1n
    Close, // 2n
}

function Calculate(length: Distance) {
    // do something here
}

不幸的是,枚举还不支持 bigint,所以这不起作用。

我尝试过类似的方法:

const Distance = {
    Far: 0n,
    Medium: 1n,
    Close: 2n
}

type Distance = typeof Distance;

function Calculate(length: Distance) {
    const answer = 1n + length;
    // Operator '+' cannot be applied to types 'bigint' and '{ Far: bigint; Medium: bigint; Close: bigint }'
}

但这似乎不起作用(我不能像使用普通枚举那样使用它)。

我知道我可以使用 BigInt() 将数字转换为 bigint,但我不想这样做。

如何创建功能类似于枚举的东西,因为它使用 bigint 而不是数字或字符串?

最佳答案

您最初使用常量对象的想法很好。您的错误是您的类型距离不是您所期望的:

Intellisense tooltip of Distance type

您的值是 bigint,因此使用 bigint 作为类型:

const Distance = {
    Far: 0n,
    Medium: 1n,
    Close: 2n
}

type Distance = bigint;

function Calculate(length: Distance) {
    const answer = 1n + length;
}

您将看到这将起作用,因为 1nlength 都将是 bigint。

关于javascript - 如何在 typescript 中使用 bigint 初始值设定项创建类似枚举的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68458593/

相关文章:

javascript - 时间转换器 : split content time with ads time

javascript - 如何从 Dropzone 的投递箱区域中删除文件?

javascript - 具有多级下拉菜单的最简单的 JQuery 动画导航栏

javascript - 更新数组中对象的值

angular - 参数类型 'action' 和 'action' 在 Angular ngrx 存储项目中不兼容

css - Angular Material如何对齐布局中心

javascript - 如何覆盖交易 View 小部件的研究

javascript - Chrome 扩展程序在执行需要 4/5 秒的代码后进行 Web 请求重定向

typescript - 为什么我的 getter/setter 不能在 TypeScript 中编译?

angular - 从服务更新组件 View ?