【发布时间】:2023-01-15 22:58:41
【问题描述】:
我有一组验证变量类型的实用函数。为了
例如string()、non_empty_string()、array()、non_null_object()等
在。它们都是谓词函数并返回一个boolean值(不是
尽管遵循 is<TypeName>() 命名约定!)。所有实用程序
函数属于 Utility 类型的对象。
interface Utility {
string: (v: unknown) => v is string;
number: ...;
natural_number: ...;
array: ...;
non_empty_array: ...;
...
...
}
type UtilityTypes = keyof Utility;
但是现在我想制作一个验证器函数来验证对象
给定实用方法。所以如果我有一个 User 类型的用户对象,
interface User {
name: string;
age: number;
isStudent?: boolean;
address: {
city: string;
state: string;
phone?: string;
}
}
然后我想使用如下模式:
type UserValidatorSchema = {
readonly name: UtilityTypes;
readonly age: UtilityTypes;
readonly "isStudent?": UtilityTypes;
readonly address: {
readonly city: UtilityTypes;
readonly state: UtilityTypes;
readonly "phone?": UtilityTypes;
}
}
const userSchema: UserValidatorSchema = {
name: "non_empty_string",
age: "natural_number",
"isStudent?": "boolean";
address: {
city: "non_empty_string";
state: "non_empty_string";
"phone?": "non_empty_string";
}
}
所有可选属性都应以“?”结尾字符,以便我的验证器 函数可以将其识别为可选属性。
现在我的问题是有什么方法可以生成UserValidatorSchema
自动从给定的User类型?
【问题讨论】:
标签: typescript