任务
逐项核对必填属性是否存在、类型是否符合声明、枚举值是否在允许集合内,输出 “<属性>:<问题>” 形式的错误。
契约
- 输入:JSON 对象:{ contract: { required: string[], types: object, enums?: object }, props: object }
- 输出:JSON 字符串数组,元素形如 “
: ”,已排序
样例
- 输入
{"contract":{"required":["label"],"types":{"label":"string","size":"string"},"enums":{"size":["sm","md"]}},"props":{"size":"xl"}}-> 期望["label:required","size:not-in-enum"]。必填的 label 缺失,且 size 的取值超出了枚举范围。 - 输入
{"contract":{"required":["label"],"types":{"label":"string"}},"props":{"label":"Save"}}-> 期望[]。完整传入属性时不会产生任何错误。
参考实现
function solve({ contract, props }) {
const errors = [];
for (const field of contract.required ?? []) if (props[field] === undefined) errors.push(field + ':required');
for (const [field, type] of Object.entries(contract.types ?? {})) {
if (props[field] !== undefined && typeof props[field] !== type) errors.push(field + ':expected-' + type);
}
for (const [field, values] of Object.entries(contract.enums ?? {})) {
if (props[field] !== undefined && !values.includes(props[field])) errors.push(field + ':not-in-enum');
}
return errors.sort();
}
为什么有效
设计系统组件在缺少契约的情况下随意加属性就会逐渐漂移。显式校验调用方式,能避免共享组件退化成每团队各一份分支。
枚举违规与类型违规分开报告,修复方向才不会有歧义。