Created
February 24, 2020 03:37
-
-
Save Sharpiro/cca8c29a1e54595a98eb03703c7549ee to your computer and use it in GitHub Desktop.
decorator validation
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 characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment