Class Static Blocks Wire Shared State
Run one-time class setup with static blocks: derived lookup tables build after static fields initialize, and multiple blocks execute in declaration order.
Code
// 静态字段先初始化,然后才轮到 static block(静态块)
class EnvTiers {
static raw = { PROD: 3, STAGING: 2, DEV: 1 };
// 静态块在类求值时运行一次:适合做派生查表这类一次性装配
static byRank = new Map();
static {
for (const [name, rank] of Object.entries(EnvTiers.raw)) {
if (typeof rank !== 'number') {
throw new TypeError('tier rank must be a number');
}
EnvTiers.byRank.set(rank, name.toLowerCase());
}
Object.freeze(EnvTiers.raw);
}
}
console.log('raw frozen :', Object.isFrozen(EnvTiers.raw));
console.log('rank 3 :', EnvTiers.byRank.get(3));
console.log('rank 1 :', EnvTiers.byRank.get(1));
console.log('lookup size :', EnvTiers.byRank.size);
// 多个静态块按声明顺序执行
class Ordered {
static trail = [];
static { Ordered.trail.push('first'); }
static { Ordered.trail.push('second'); }
}
console.log('block order :', Ordered.trail.join(', '));Output
Captured from a sandboxed run of this snippet in the build pipeline.
raw frozen : true
rank 3 : prod
rank 1 : dev
lookup size : 3
block order : first, secondHow it works
Class Static Blocks Wire Shared State comes down to the classes EnvTiers and Ordered.
The file repeats itself only inside for (const [name, rank] of Object.entries(EnvTiers.raw)). Invalid states are rejected up front: it throws TypeError instead of continuing with bad data.
Watch out for
- The guard
typeof rank !== 'number'short-circuits the flow with an earlythrowwhen its condition holds.
Putting it to use
The demo output is labeled (lookup size :, block order :), so every printed line maps back to its originating operation.
Core lines
throw new TypeError('tier rank must be a number');
static byRank = new Map();
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- Is there a failure path for bad input?
- It throws `TypeError` before any real work runs, via the guard `typeof rank !== 'number'` — handle it at the call site or let it propagate deliberately.
- Is anything beyond the standard library required?
- Nothing beyond the standard library — the snippet is dependency-free.
Report a problem with this exampleOpens a pre-filled issue on GitHub.