本文介绍如何在typescript项目中使用yup库动态生成接口和验证模式,尤其是在处理具有动态定义键的对象时,并确保至少一个键具有有效值。

挑战: 我们需要验证一个对象,其键是动态定义的,并且需要确保至少一个键的值有效。有效的键及其类型存储在一个元数据映射中:
<code class="typescript">const metadataMap = {
userId: Number,
utmSource: String,
utmMedium: String,
utmCampaign: String,
};</code>解决方案: 我们分三个步骤解决这个问题:
步骤一:生成TypeScript接口
为了动态生成TypeScript接口,我们利用键入映射和keyof类型:
<code class="typescript">type Metadata = {
[k in keyof typeof metadataMap]?: typeof metadataMap[k] extends NumberConstructor ? number : string;
};</code>这确保了Metadata接口会根据metadataMap的更新自动调整。生成的接口如下所示:
<code class="typescript">interface Metadata {
userId?: number;
utmSource?: string;
utmMedium?: string;
utmCampaign?: string;
}</code>步骤二:动态生成Yup模式
我们使用object.keys和reduce方法动态创建Yup模式,将每个键映射到相应的Yup验证器:
<code class="typescript">const metadataSchema = yup.object().shape(
Object.keys(metadataMap).reduce((schema, key) => {
const type = metadataMap[key as keyof typeof metadataMap];
if (type === Number) {
schema[key] = yup.number().optional();
} else if (type === String) {
schema[key] = yup.string().optional();
}
return schema;
}, {} as Record<string, any>)
);</code>这避免了硬编码,并确保模式会随着metadataMap的变化而自动更新。
步骤三:添加“至少一个键”规则
为了确保至少一个键具有有效值,我们在Yup模式中添加.test方法:
<code class="typescript">metadataSchema.test(
'atLeastOneKey',
'Metadata must have at least one valid key.',
(value) => {
if (!value || typeof value !== 'object') return false;
const validKeys = Object.keys(metadataMap) as (keyof typeof metadataMap)[];
return validKeys.some((key) => value[key] !== undefined);
}
);</code>这个测试会:
metadataMap动态获取有效键。undefined。结果:
以下示例展示了最终模式的行为:
<code class="typescript">const exampleMetadata = {
userId: undefined,
utmSource: 'Google',
extField: 'invalid', // This key is ignored
};
metadataSchema.validate(exampleMetadata)
.then(() => console.log('Validation successful!'))
.catch((err) => console.error('Validation failed:', err));</code>在这个例子中,验证成功,因为utmSource是一个有效键且值不为undefined,即使userId为undefined,extField也不在metadataMap中。 这个方法有效地结合了TypeScript的静态类型检查和Yup的运行时验证,提供了灵活且健壮的数据验证方案。
以上就是使用 Yup 在 TypeScript 中动态生成接口和验证模式的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号