Skip to content

Instantly share code, notes, and snippets.

@sibelius
Forked from gtkatakura/types-for-moongose.ts
Created July 22, 2018 23:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sibelius/06e01d9d34e0c41e5d6b396e45ea0446 to your computer and use it in GitHub Desktop.
Save sibelius/06e01d9d34e0c41e5d6b396e45ea0446 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,
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment