如果返回的对象不是类型T
,则返回默认值,是否有一种方法可以使其工作.
仅通过添加在运行时从JSON.parse
判断结果的验证代码.非类型化世界和类型化世界之间的这些边缘总是提出这种挑战.
有一些库可以帮助您使用它们的方法编写形状(类型)的定义,并返回both运行时验证函数和TypeScript类型.我现在使用的是zod
,但它不是唯一的一个在那里.
FWIW,这里有一个使用zod
的例子,但是,还有其他的库,或者您可以为您的类型编写自己的自定义代码.
首先,定义了模式,并从中提取一个方便的类型别名:
// A user with a `name` and `email`, both strings
const userSchema = z.object({
name: z.string(),
email: z.string().email(), // Zod has some validators for common things like email addresses
});
type User = z.infer<typeof userSchema>;
在这里,User
类型是{name: string; email: string;}
.
然后你的函数将接受并使用Zod schema:
const safeJSONParse = <Schema extends ZodTypeAny>(
json: string,
schema: Schema,
defaultValue?: z.infer<Schema>
): z.infer<Schema> | undefined => {
try {
const result = schema.parse(JSON.parse(json));
return result;
} catch (e: any) {
return defaultValue;
}
};
然后,在解析用户的JSON时使用该模式:
const user = safeJSONParse(userJson, userSchema);
if (user) {
// It's valid
console.log(user.name);
}
Playground example