Last active
May 15, 2018 10:28
-
-
Save tbuschto/8dcc6002095664410018d3a042d9e603 to your computer and use it in GitHub Desktop.
positive 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 { 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