Effect CommunityEC
Effect Communityβ€’3y agoβ€’
74 replies
Tim Smart

Class Version of Schema

Anyone thought about creating a class version of schema? I'm sure @Patrick Roza has πŸ™‚

interface SchemaClass<I, A extends Record<string, any>>
  extends Schema.Schema<I, A> {
  new (props: A): A

  // maybe add the schema here?
  readonly schema: Schema.Schema<I, A>
  //                                ^ can you reference the constructor type?
}

const SchemaClass = <I, A extends Record<string, any>>(
  schema: Schema.Schema<I, A>,
): SchemaClass<I, A> => {
  const validate = Schema.validate(schema)
  return class {
    static readonly ast = schema.ast
    constructor(props: A) {
      Object.assign(this, validate(props))
    }
  } as any
}

class User extends SchemaClass(
  Schema.struct({
    name: Schema.string,
    age: Schema.number,
  }),
) {}
Was this page helpful?