I have a set of utility functions that validate the type of a variable. Some examples include string()
, non_empty_string()
, array()
, non_null_object()
, and others. These functions are all predicate functions that return a boolean
value (although they do not follow the conventional naming pattern is<TypeName>()
). All these utility functions belong to an object of type Utility
.
interface Utility {
string: (v: unknown) => v is string;
number: ...;
natural_number: ...;
array: ...;
non_empty_array: ...;
...
...
}
type UtilityTypes = keyof Utility;
Now, I want to create a validation function that can validate objects using these utility methods. For example, if I have a user object of type User
,
interface User {
name: string;
age: number;
isStudent?: boolean;
address: {
city: string;
state: string;
phone?: string;
}
}
I would like to define a schema like the following:
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";
}
}
All optional properties in the schema should end with a "?" character to indicate that they are optional for the validator function.
My question now is whether there is a way to automatically generate the UserValidatorSchema
based on the given User
type?