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.

TypescriptSecurity Boundaries

Code

typescriptsnippet
21 lines
// 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-table

How 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

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.