实现说明
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);
}