Created
July 21, 2018 23:45
-
-
Save gtkatakura/39debf900c6b4f78bae40ccc3bab6d42 to your computer and use it in GitHub Desktop.
This file contains 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
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
graphql/graphql-js#574