Skip to content

Instantly share code, notes, and snippets.

@gtkatakura
Created July 21, 2018 23:45
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gtkatakura/39debf900c6b4f78bae40ccc3bab6d42 to your computer and use it in GitHub Desktop.
Save gtkatakura/39debf900c6b4f78bae40ccc3bab6d42 to your computer and use it in GitHub Desktop.
type TypesDefinition =
| StringConstructor
| BooleanConstructor
| DateConstructor
type FieldDefinition = {
type: TypesDefinition,
required?: boolean,
default?: boolean,
}
type SchemaDefinition = {
[path: string]: FieldDefinition,
}
type FromTypeDefinition<T extends TypesDefinition> =
T extends StringConstructor ? string :
T extends BooleanConstructor ? boolean :
T extends DateConstructor ? Date :
never
type OptionalFields<T extends SchemaDefinition> = {
[K in keyof T]: T[K]['required'] extends boolean ? never : K
}[keyof T]
type RequiredFields<T extends SchemaDefinition> = Exclude<keyof T, OptionalFields<T>>
type ExtractModelDefinition<T extends SchemaDefinition> =
& { [K in RequiredFields<T>]: FromTypeDefinition<T[K]['type']> }
& { [K in OptionalFields<T>]?: FromTypeDefinition<T[K]['type']> }
const userSchemaConfig = {
name: {
type: String,
required: true,
},
password: {
type: String,
hidden: true,
},
email: {
type: String,
required: false,
index: true,
},
active: {
type: Boolean,
default: true,
},
}
type User = ExtractModelDefinition<typeof userSchemaConfig>
/* =>
{
name: string,
email: string,
password?: string,
active? boolean,
}
*/
@gtkatakura
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment