What I would ideally do is:
enum Distance {
Far: 0n,
Medium, // 1n
Close, // 2n
}
function Calculate(length: Distance) {
// do something here
}
Unfortunately enums do not support bigints yet, so that doesn't work.
I've tried something like:
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 }'
}
But that doesn't seem to work (I can't use it as I would a normal enum).
I know I can just cast the number to a bigint with BigInt()
but I'd rather not do that.
How can I create something that functions like an enum because that uses bigints instead of numerals or strings?
Your initial idea of using a constant object instead is good. Your mistake is your type Distance
that isn't what you expect:
Your values are bigints, therefore use bigint
as type:
const Distance = {
Far: 0n,
Medium: 1n,
Close: 2n
}
type Distance = bigint;
function Calculate(length: Distance) {
const answer = 1n + length;
}
You'll see that this will work, since both 1n
and length
will be bigints.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.