Type-safe utilities for readonly and const data structures, including bidirectional mappings, array transformations, and object manipulation, along with general typing utilities
npm install @xlabs-xyz/const-utils
Type-safe utilities for readonly and const data structures, including bidirectional mappings, array transformations, and object manipulation. Also includes general-purpose typing utilities – const/readonly is the primary theme, but not the only one.
- Type Utilities – core types, mutability helpers, RoUint8Array
- Array Utilities – const-preserving array operations
- Object Utilities – type-safe object manipulation
- Const Maps – type-safe bidirectional mappings from nested specs
- String Utilities – type-preserving case functions
- Branding – hierarchical type branding with tag accumulation
- Aliasing – suppress union/type expansion in IDE tooltips
Core type utilities for readonly data and type manipulation.
- Tuple, NeTuple – mutable tuple, non-empty variant
- RoTuple, RoNeTuple – readonly tuple, non-empty variant
- RoArray – readonly T[]
- RoPair – readonly [T, U]
A truly readonly Uint8Array type that correctly types subarray, valueOf, and callback methods. See RoUint8Array.md for implementation details.
- Ro, DeepRo – shallow/deep readonly (handles RoUint8Array)
- Mutable, DeepMutable – shallow/deep mutable
- ro(value), deepRo(value) – runtime casts
- mutable(value), deepMutable(value) – runtime casts
- Function – generic function type (more powerful than built-in)
- Opts – make all properties optional and allow undefined
- Simplify – flatten intersection types for readability
- Widen – widen literal types to their base types
- HeadTail – pattern match on tuple head/tail
- Extends, IsAny – type predicates
- assertType – assert a value extends a type (for complex generics)
Const-preserving array operations that maintain tuple types through transformations.
``typescript`
const tup = [1, 2, 3] as const;
tup.map(x => x.toString()); // => string[] (loses tuple structure)
mapTo(tup)(x => x.toString()); // => readonly [string, string, string]
mapTo(1)(x => x.toString()); // => string (also works on scalars)
`typescript`
entries([10, 20, 30] as const); // => [[0, 10], [1, 20], [2, 30]]
valueIndexEntries(["a", "b"]); // => [["a", 0], ["b", 1]]
`typescript`
range(3); // => [0, 1, 2]
flatten([[1, 2], [3]]); // => [1, 2, 3]
chunk([1, 2, 3, 4, 5], 2); // => [[1, 2], [3, 4], [5]]
zip([["a", "b"], [1, 2]]); // => [["a", 1], ["b", 2]]
column([["a", 1], ["b", 2]], 0); // => ["a", "b"]
pickWithOrder(["a", "b", "c"], [2, 0]); // => ["c", "a"]
filterIndexes(["a", "b", "c"], [0, 2]); // => ["a", "c"]
`typescript`
intersect(["a", "b", "c"], ["b", "c", "d"]); // => ["b", "c"]
union(["a", "b"], ["b", "c"]); // => ["a", "b", "c"]
difference(["a", "b", "c"], ["b"]); // => ["a", "c"]
- TupleRange, Range – [0, 1, ..., L-1]TupleWithLength
- – tuple of L elements of type TFlatten
- , InnerFlatten, UnflattenChunk
- , Zip, ColumnCartesian
- – Cartesian product typeTupleFilter
- , TupleFilterOutIntersect
- , Union, Difference
Type-safe object manipulation.
`typescript
pick({ a: 1, b: 2, c: 3 }, ["a", "b"]); // => { a: 1, b: 2 }
omit({ a: 1, b: 2, c: 3 }, "c"); // => { a: 1, b: 2 }
replace({ a: 1, b: 2 }, "a", "new"); // => { a: "new", b: 2 }
spread({ a: 1, n: { b: 2, c: 3 } }, "n"); // => { a: 1, b: 2, c: 3 }
nest({ a: 1, b: 2, c: 3 }, "n", ["b", "c"]); // => { a: 1, n: { b: 2, c: 3 } }
// Deep operations with path support
deepOmit(obj, ["users", anyKey, "password"]); // remove password from all users
fromEntries([["a", 1], ["b", 2]] as const); // => { a: 1, b: 2 } (typed)
`
constMap provides a way to define type-safe mappings from hierarchical const data specifications.
`typescript`
const networks = [[
"Mainnet", [
["Ethereum", 1n],
["Bsc", 56n],
["Polygon", 137n],
]], [
"Testnet", [
["Ethereum", 5n],
["Sepolia", 11155111n],
]]
] as const satisfies MappingEntries;
This specifies a relationship between EVM chain ids and their respective chains and networks. It is a shortened way to specify the full Cartesian product:
`typescript`
[
["Mainnet", "Ethereum", 1n],
["Mainnet", "Bsc", 56n],
["Mainnet", "Polygon", 137n],
["Testnet", "Ethereum", 5n],
["Testnet", "Sepolia", 11155111n],
]
`typescript
const chainId = constMap(networks);
chainId("Mainnet", "Ethereum"); // => 1n (typed as literal)
chainId("Testnet", "Sepolia"); // => 11155111n
chainId.has("Mainnet", "Solana"); // => false
chainId.get("Mainnet", "Solana"); // => undefined
const testnetChainId = chainId.subMap("Testnet");
testnetChainId("Sepolia"); // => 11155111n
`
By default, the first n-1 columns are keys and the last column is the value. Custom shapes allow different mappings:
`typescript
// Reverse lookup: chainId -> [network, chain]
const networkAndChain = constMap(networks, [2, [0, 1]]);
networkAndChain(1n); // => ["Mainnet", "Ethereum"]
// Chain -> networks (one-to-many)
const networksForChain = constMap(networks, [1, 0]);
networksForChain("Ethereum"); // => ["Mainnet", "Testnet"]
`
Supports bigint and boolean keys natively (unlike plain objects which coerce them to strings).
Type-preserving string case functions.
`typescript`
uppercase("hello"); // => "HELLO" (typed as Uppercase<"hello">)
lowercase("HELLO"); // => "hello"
capitalize("hello"); // => "Hello"
uncapitalize("Hello"); // => "hello"
otherCap("hello"); // => "Hello" (toggles first letter case)
Branding allows you to create distinct types from a base type by attaching tags, to get around issues that stem from TypeScript using structural typing (duck-typing) where type UserId = string; and type ProductId = string; are considered equivalent, leading to accidental mixing of values that share the same underlying type but represent different concepts.
The key feature of this implementation on top of normal branding mechanics is that tags accumulate hierarchically. When you brand a type that's already branded, the new tag is added to the existing set of tags rather than replacing them:
`typescript`
type UserId = Brand
type AdminId = Brand
This allows for type hierarchies where more specific branded types inherit the constraints of their parent brands, but can be covariantly passed to functions that expect the parent type:
`typescript`
function processUser(userId: UserId): void;
processUser(adminId); // works because AdminId is a subtype of UserId
brand() captures the inferred type without requiring its explicit specification. Useful when branding complex types:
`typescript
import { address } from "@solana/kit";
const userAddress = brand<"user">()(address("3WxjT2rCBfncPvDHsnBc9nB3MQo2eYk25tV2SmC9E5HM"));
// => Brand
$3
-
Brand – apply a brand tag to a type
- Branded – the underlying branded type structure
- Unbrand – strip branding, recover the base type
- ExtractTags – get the tags from a branded type
- IsBranded – check if a type is branded
- SameBrand – check if two types have identical brands
- PreserveBrand – transfer brand from T to R if base types match
- BrandedSubArray – helper for branded Uint8Arrays with correct subarray return type
- brand – runtime branding functionAliasing
A hack to make large union types more readable in IDE tooltips.
TypeScript always expands union types like
type Letter = "a" | "b" | ... | "z" in tooltips. This module provides a way to suppress that expansion:`typescript
type Letter = "a" | "b" | "c" | "d" | "e" | "f";
interface AllLetters extends SuppressExpansion {}interface LetterAliases {
AllLetters: [Letter, AllLetters];
}
type Test = ApplyAliases; // => keyof AllLetters (not expanded)
`Subsets can also be registered:
`typescript
interface Vowels extends SuppressExpansion<"a" | "e"> {}
interface LetterAliases {
Vowels: ["a" | "e", Vowels];
}type Test = ApplyAliases; // => keyof Vowels | "f"
`$3
-
SuppressExpansion – create an interface that suppresses union expansion
- ApplyAliases – apply registered aliases to a union
- Expand – re-expand an alias back to its union
- Opaque