题目
定义 FieldError 为 REQUIRED、INVALID_EMAIL、TOO_YOUNG、INVALID_TYPE 四个字面量的联合,Validator
解题思路
每个校验器只返回封闭联合中的错误码或 null,调用方无需解析字符串。required 先 trim 再判断是否为空;email 用一个简单正则检查基本的邮箱形状;minimumAge 先判断运行时类型是否为有限数字,不是则返回 INVALID_TYPE,是再比较是否达到 18。validate 使用剩余参数接收多个规则,循环中一旦拿到非空结果就返回。主流程按 email、age、name 的固定顺序构造检查数组,再把非空结果写入 errors,最后用 every 计算 valid。
参考实现要点
检查数组显式标注为 Array<[keyof Form, FieldError | null]>,字段名只能是表单的键。errors 使用 Partial<Record<keyof Form, FieldError>>,只包含失败的字段,空对象序列化为 {}。valid 由所有检查结果共同决定,不能只看 errors 的键数量。固定顺序保证输出键顺序稳定,便于与 expected 逐字比较。
常见错误
校验器返回布尔值,错误原因丢失,UI 无法区分必填与格式错误。按 Object.keys 遍历表单,字段顺序随输入变化,错误映射的顺序不稳定。minimumAge 先做数值比较再判断类型,字符串会被隐式转换或得到错误的错误码。validate 执行完所有规则再返回最后一个错误,而不是第一个错误。
验证方式
用 tsc –strict 编译,确认检查数组只能使用表单键与合法错误码。运行三个样例并比对 JSON。补充测试:年龄恰好 18 应通过;仅含空格的姓名应返回 REQUIRED;邮箱非法且姓名为空时两个字段都应出现在 errors 中。最后确认 valid 只在 errors 为空时为 true。
代码示例
declare const input: string;
type FieldError = 'REQUIRED' | 'INVALID_EMAIL' | 'TOO_YOUNG' | 'INVALID_TYPE';
type Validator<T> = (value: T) => FieldError | null;
const required = (value: string): FieldError | null =>
value.trim() === '' ? 'REQUIRED' : null;
const email = (value: string): FieldError | null =>
/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value) ? null : 'INVALID_EMAIL';
const minimumAge = (value: number): FieldError | null => {
if (typeof value !== 'number' || !Number.isFinite(value)) return 'INVALID_TYPE';
return value >= 18 ? null : 'TOO_YOUNG';
};
function validate<T>(value: T, ...rules: Array<Validator<T>>): FieldError | null {
for (const rule of rules) {
const error = rule(value);
if (error) return error;
}
return null;
}
interface Form {
email: string;
age: number;
name: string;
}
interface Spec {
form: Form;
}
const spec = JSON.parse(input) as Spec;
const checks: Array<[keyof Form, FieldError | null]> = [
['email', validate(spec.form.email, required, email)],
['age', validate(spec.form.age, minimumAge)],
['name', validate(spec.form.name, required)],
];
const errors: Partial<Record<keyof Form, FieldError>> = {};
for (const [field, error] of checks) {
if (error) errors[field] = error;
}
console.log(JSON.stringify({ valid: checks.every(([, error]) => error === null), errors }));