Created
February 24, 2020 03:37
-
-
Save Sharpiro/cca8c29a1e54595a98eb03703c7549ee to your computer and use it in GitHub Desktop.
Revisions
-
Sharpiro created this gist
Feb 24, 2020 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal 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)