Skip to content

Instantly share code, notes, and snippets.

@tbuschto
Last active May 15, 2018 10:30
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 tbuschto/bd36901f97cfdd4f046f75f422b8d05e to your computer and use it in GitHub Desktop.
Save tbuschto/bd36901f97cfdd4f046f75f422b8d05e to your computer and use it in GitHub Desktop.
generic type check decorator
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