Last active
May 15, 2018 10:30
-
-
Save tbuschto/bd36901f97cfdd4f046f75f422b8d05e to your computer and use it in GitHub Desktop.
generic type check decorator
This file contains 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
import 'reflect-metadata'; | |
import { ui } from 'tabris'; | |
function check(prototype: object, property: string) { | |
const sym = Symbol(); | |
const constr = Reflect.getMetadata('design:type', prototype, property); | |
Object.defineProperty(prototype, property, { | |
enumerable: true, | |
set(value: any) { | |
if (!(value instanceof constr) && (typeof value !== constr.name.toLocaleLowerCase())) { | |
throw new Error(`Failed to set "${property}": ${constr.name} expected, got ${typeof value}`); | |
} | |
this[sym] = value; | |
}, | |
get() { | |
return this[sym]; | |
} | |
}); | |
} | |
class Person { | |
@check public name: string; | |
@check public married: boolean; | |
} | |
const jack = new Person(); | |
try { | |
Object.assign(jack, JSON.parse( | |
'{"name": "Jack Bauer", "married": "yes"}' | |
)); // Error: Failed to set "married": Boolean expected, got string | |
} catch(ex) { | |
console.error(ex); | |
} | |
try { | |
Object.assign(jack, JSON.parse( | |
'{"name": "Jack Bauer", "married": true}' | |
)); | |
} catch(ex) { | |
console.error(ex); | |
} | |
ui.contentView.append(<textView>{jack.name + ' is married: ' + jack.married}</textView>); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment