A powerful, type-safe and flexible bitfield utility for JavaScript and TypeScript.
Supports bigint, multiple input formats, immutability, and dynamic class creation.
- β‘ Type-safe flags
- π§ Accepts multiple input formats (string, bigint, arrays, instances)
- π’ Uses
bigint(no 32-bit limits) - π§© Dynamic bitfield classes with
createBitfield - π Mutable and immutable modes (via
Object.freeze) - π¦ Fully typed for TypeScript
- π§ͺ Designed for reliability and testing
npm install sybitsimport { createBitfield } from "your-package-name";
const Permissions = createBitfield([
"READ",
"WRITE",
"DELETE"
] as const);
const perms = new Permissions([
"READ",
"WRITE"
]);
perms.has("READ"); // true
perms.has("DELETE"); // falseconst Permissions = createBitfield([
"READ",
"WRITE",
"DELETE"
] as const);const PermissionsBits = {
READ: 1n << 0n,
WRITE: 1n << 1n,
DELETE: 1n << 2n
}
const Permissions = createBitfield(
PermissionsBits,
// Default Bits ( READ and WRITE )
PermissionsBits.READ | PermissionsBits.WRITE
);perms.add("READ");
perms.remove("WRITE");perms.has("READ"); // trueperms.add(
"READ",
["WRITE", "DELETE"],
1n,
new Permissions("READ")
);perms.missing(["READ", "WRITE", "DELETE"]);
// β ["WRITE", "DELETE"]perms.toArray();
// β ["READ", "WRITE"]perms.serialize();
// β { READ: true, WRITE: true, DELETE: false }for (const flag of perms) {
console.log(flag);
}If the instance is frozen, operations return a new instance:
const frozen = Object.freeze(new Permissions("READ"));
const updated = frozen.add("WRITE");
updated.has("WRITE"); // true
frozen.has("WRITE"); // falseperms.bits; // bigintPermissions.Flags.READ; // bigint
Permissions.ALL; // bigint (all flags combined)The library automatically resolves inputs like:
- string β flag
- bigint β raw value
- Bitfield β its bits
- arrays β recursively flattened and combined
- Always use
as constwhen defining flags arrays to preserve type safety toJSON()returns a number (may lose precision for very large bitfields)