Skip to content

Instantly share code, notes, and snippets.

@Sharpiro
Created February 24, 2020 03:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sharpiro/cca8c29a1e54595a98eb03703c7549ee to your computer and use it in GitHub Desktop.
Save Sharpiro/cca8c29a1e54595a98eb03703c7549ee to your computer and use it in GitHub Desktop.
decorator validation
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