Skip to content

Instantly share code, notes, and snippets.

@tbuschto
Last active May 15, 2018 10:28
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/8dcc6002095664410018d3a042d9e603 to your computer and use it in GitHub Desktop.
Save tbuschto/8dcc6002095664410018d3a042d9e603 to your computer and use it in GitHub Desktop.
positive decorator
import { ui } from 'tabris';
function positive(prototype: object, property: string) {
const sym = Symbol();
Object.defineProperty(prototype, property, {
enumerable: true,
set(value: number) {
if (value < 0) {
throw new Error('Positive number expected');
}
this[sym] = value;
},
get() {
return this[sym];
}
});
}
class Person {
@positive public age: number;
}
let person = new Person();
try {
person.age = 23; // OK
person.age = -23; // Error: Positive number expected
} catch(ex) {
console.error(ex);
} finally {
ui.contentView.append(<textView>{'Age:' + person.age}</textView>);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment