Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
coerceBooleanProperty as property decorator
function coerceBooleanProperty(prop: unknown): boolean {
return !!prop;
}
const CoerceBoolean: PropertyDecorator = (proto, prop) => {
const values = new WeakMap();
Object.defineProperty(proto, prop, {
get() {
return values.get(this)
},
set(value: unknown) {
values.set(this, coerceBooleanProperty(value))
},
enumerable: true
})
}
class Example {
@CoerceBoolean prop = false;
get not() {
return !this.prop;
}
}
let ex = new Example;
console.log(ex, ex.prop);
(ex as any).prop = "lol";
console.log(ex, ex.prop);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment