Skip to content

Instantly share code, notes, and snippets.

@rawnly
Created March 27, 2022 16:42
Show Gist options
  • Save rawnly/ec8f0e62ce6d2651c9ae7a77138dc813 to your computer and use it in GitHub Desktop.
Save rawnly/ec8f0e62ce6d2651c9ae7a77138dc813 to your computer and use it in GitHub Desktop.
// 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