Guest User

Untitled

a guest
Jul 21st, 2018
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. type TypesDefinition =
  2. | StringConstructor
  3. | BooleanConstructor
  4. | DateConstructor
  5.  
  6. type FieldDefinition = {
  7. type: TypesDefinition,
  8. required?: boolean,
  9. default?: boolean,
  10. }
  11.  
  12. type SchemaDefinition = {
  13. [path: string]: FieldDefinition,
  14. }
  15.  
  16. type FromTypeDefinition<T extends TypesDefinition> =
  17. T extends StringConstructor ? string :
  18. T extends BooleanConstructor ? boolean :
  19. T extends DateConstructor ? Date :
  20. never
  21.  
  22. type OptionalFields<T extends SchemaDefinition> = {
  23. [K in keyof T]: T[K]['required'] extends boolean ? never : K
  24. }[keyof T]
  25.  
  26. type RequiredFields<T extends SchemaDefinition> = Exclude<keyof T, OptionalFields<T>>
  27.  
  28. type ExtractModelDefinition<T extends SchemaDefinition> =
  29. & { [K in RequiredFields<T>]: FromTypeDefinition<T[K]['type']> }
  30. & { [K in OptionalFields<T>]?: FromTypeDefinition<T[K]['type']> }
  31.  
  32. const userSchemaConfig = {
  33. name: {
  34. type: String,
  35. required: true,
  36. },
  37. password: {
  38. type: String,
  39. hidden: true,
  40. },
  41. email: {
  42. type: String,
  43. required: false,
  44. index: true,
  45. },
  46. active: {
  47. type: Boolean,
  48. default: true,
  49. },
  50. }
  51.  
  52. type User = ExtractModelDefinition<typeof userSchemaConfig>
  53. /* =>
  54. {
  55. name: string,
  56. email: string,
  57. password?: string,
  58. active? boolean,
  59. }
  60. */
Add Comment
Please, Sign In to add comment