← 中文资源

简体中文版本

const 数组派生白名单联合

用 as const 数组派生封闭联合类型,配合谓词把字符串收窄进白名单:清单外的命令在分发前就被拒绝,新增命令只需改一行。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

dispatched: deploy
rejected: whoami
dispatched: status
rejected: drop-table

实现说明

const 数组派生白名单联合的核心是函数 isCommand、dispatch。 文件的主干是一个循环——for (const raw of ['deploy', 'whoami', 'status', 'drop-table'])。

使用要点

  • 跑完文件,输出里会留下标记——rejected:、dispatched:。

常见问题

包管理器会看到什么?

一份空的依赖清单。示例没有需要抓取的导入。 文件在加载时定义 isCommand、dispatch。

主要签名是 function isCommand(input: string)

核心语句

const COMMAND_ALLOWLIST = ['deploy', 'rollback', 'status'] as const;
return (COMMAND_ALLOWLIST as readonly string[]).includes(input);

代码示例

// 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);
}