Created
April 7, 2020 19:26
-
-
Save P4/e3e14d5bc3869526ac2fc65c71a39ec4 to your computer and use it in GitHub Desktop.
coerceBooleanProperty as property 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
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 | |
}) | |
} |
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
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