我理想的做法是:
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 而不是数字或字符串?
最佳答案
您最初使用常量对象的想法很好。您的错误是您的类型距离
不是您所期望的:
您的值是 bigint,因此使用 bigint
作为类型:
const Distance = {
Far: 0n,
Medium: 1n,
Close: 2n
}
type Distance = bigint;
function Calculate(length: Distance) {
const answer = 1n + length;
}
您将看到这将起作用,因为 1n
和 length
都将是 bigint。
关于javascript - 如何在 typescript 中使用 bigint 初始值设定项创建类似枚举的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68458593/