首页 > 解决方案 > 如何在打字稿中使用 bigint 初始化程序创建一个类似枚举的对象?

问题描述

我最理想的做法是:

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()但我宁愿不这样做。

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

标签: javascripttypescript

解决方案


您最初使用常量对象的想法很好。您的错误是您的错误type Distance,这不是您所期望的:

距离类型的智能感知工具提示

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

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

type Distance = bigint;

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

你会看到这会起作用,因为两者1n都是lengthbigints。


推荐阅读