Const Arrays Derive Allowlist Unions
Derive a closed union from an as const allowlist array and narrow strings into it with a predicate, so unknown commands are rejected before dispatch.
Code
// as const 数组派生封闭联合:白名单新增一项,联合类型随之更新
const COMMAND_ALLOWLIST = ['deploy', 'rollback', 'status'] as const;
type Command = (typeof COMMAND_ALLOWLIST)[number];
// 谓词把任意字符串收窄(narrow)进白名单联合
function isCommand(input: string): input is Command {
return (COMMAND_ALLOWLIST as readonly string[]).includes(input);
}
function dispatch(raw: string): void {
if (!isCommand(raw)) {
console.log('rejected:', raw);
return;
}
console.log('dispatched:', raw);
}
for (const raw of ['deploy', 'whoami', 'status', 'drop-table']) {
dispatch(raw);
}Output
Captured from a sandboxed run of this snippet in the build pipeline.
dispatched: deploy
rejected: whoami
dispatched: status
rejected: drop-tableHow the snippet works
Const Arrays Derive Allowlist Unions is built around the functions isCommand and dispatch.
for (const raw of ['deploy', 'whoami', 'status', 'drop-table']) is the loop that carries the per-item work.
Applying it
The primary signature is function isCommand(input: string)
The demo output is labeled (rejected:, dispatched:), so each line of output maps back to the operation it came from.
Statements that matter
const COMMAND_ALLOWLIST = ['deploy', 'rollback', 'status'] as const;
return (COMMAND_ALLOWLIST as readonly string[]).includes(input);
Interactive Tools for This Topic
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.
FAQ
- What does the package manager see?
- An empty dependency file. The snippet imports nothing that needs fetching. The file defines `isCommand`, `dispatch` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.