Created
March 27, 2022 16:42
-
-
Save rawnly/ec8f0e62ce6d2651c9ae7a77138dc813 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// for custom model validation (inspired by ZOD) | |
type StringType = { | |
_type: 'STRING' | |
} | |
type DateType = { | |
_type: 'DATE' | |
} | |
type NumberType = { | |
_type: 'NUMBER' | |
} | |
type Type = DateType | StringType | NumberType | |
type InferType<T> = T extends StringType | |
? string | |
: ( | |
T extends DateType | |
? Date | |
: ( T extends NumberType ? number : T ) | |
) | |
type Infer<T extends Record<any, Type>> = { | |
[K in keyof T]: InferType<T[K]> | |
} | |
const string = (): StringType => ( { _type: 'STRING' } ) | |
const date = (): DateType => ( { _type: 'DATE' } ) | |
const number = (): NumberType => ( { _type: 'NUMBER' } ) | |
// USAGE | |
const UserModel = { | |
name: string(), | |
bday: date(), | |
age: number() | |
} | |
type UserModel = Infer<typeof UserModel> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment