Skip to content

Instantly share code, notes, and snippets.

@Sharpiro
Created February 24, 2020 03:37
Show Gist options
  • Select an option

  • Save Sharpiro/cca8c29a1e54595a98eb03703c7549ee to your computer and use it in GitHub Desktop.

Select an option

Save Sharpiro/cca8c29a1e54595a98eb03703c7549ee to your computer and use it in GitHub Desktop.

Revisions

  1. Sharpiro created this gist Feb 24, 2020.
    58 changes: 58 additions & 0 deletions index.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,58 @@
    function Validate<T extends { new(...args: any[]): {} }>(constructor: T) {
    return class extends constructor {
    errors: string[]

    constructor(...items: any[]) {
    super(...items)
    this.errors = []
    for (const x in this) {
    if (this[x] == undefined) {
    this.errors.push(`property '${x}' was undefined on class '${constructor.name}'`)
    }
    }
    }
    }
    }

    function validateErrors(obj: any) {
    if (!obj.errors) {
    console.warn("did not find obj metadata")
    return
    }
    if (obj.errors.length) {
    console.error(obj.errors)
    }
    }

    type ExampleInit = Omit<Example, "doSomething" | "value" | "height">

    @Validate
    class Example {
    height = 1
    name!: string
    age!: number
    temp?: boolean

    constructor(init: ExampleInit) {
    Object.assign(this, init)
    }

    public get value(): string {
    return "computed value"
    }

    doSomething() {
    console.log("something is called by func")
    }
    }

    // const e = new Example({ name: 'Graham', age: 12 })
    // const e = new Example({ name: 'Graham', age: 12, temp: true })
    const e = new Example({ name: 'Graham', age: undefined as any })

    // e.doSomething()
    console.log("done\n\n\n")
    console.log(e)
    console.log(e instanceof Example)

    validateErrors(e)