实现说明
活动部件是函数 validate。
在这里做循环的是 for (const item of error.errors as FieldError[])。守卫条件成立时抛出 AggregateError,而不是返回一个假值。
使用要点
- 守卫
errors.length > 0满足时靠提前的throw短路流程。 - 演示输出是带标签的(
message:、field:),每个操作都会留下自己的一行标注。
常见问题
坏输入有失败路径吗?
守卫处(errors.length > 0)会抛出 AggregateError,非法状态到不了主逻辑。
需要标准库之外的东西吗?
除标准库外不引入任何东西——这个示例没有依赖。 文件在加载时定义 validate。
入口签名:function validate(input: Record<string, unknown>)
核心语句
throw new AggregateError(errors, 'validation failed with ' + errors.length + ' errors');
代码示例
type FieldError = { field: string; message: string };
function validate(input: Record<string, unknown>): void {
const errors: FieldError[] = [];
if (typeof input.email !== 'string') {
errors.push({ field: 'email', message: 'email is required' });
}
if (typeof input.age !== 'number' || input.age < 18) {
errors.push({ field: 'age', message: 'age must be 18 or older' });
}
if (!input.accepted) {
errors.push({ field: 'accepted', message: 'terms must be accepted' });
}
if (errors.length > 0) {
throw new AggregateError(errors, 'validation failed with ' + errors.length + ' errors');
}
}
try {
validate({ email: 42, age: 16, accepted: false });
} catch (error) {
if (error instanceof AggregateError) {
console.log('message:', error.message);
for (const item of error.errors as FieldError[]) {
console.log('field:', item.field, '->', item.message);
}
}
}