Skip to content

Instantly share code, notes, and snippets.

@GaetanRdn
Created October 3, 2021 10:51
Show Gist options
  • Save GaetanRdn/74e0b0cf18f9202d1c7fe4d80af68373 to your computer and use it in GitHub Desktop.
Save GaetanRdn/74e0b0cf18f9202d1c7fe4d80af68373 to your computer and use it in GitHub Desktop.
Allow to coerce boolean input, this decorator can Be applied on property or setter
export function CoerceBoolean() {
return function(target: any, key: string, propertyDescriptor?: PropertyDescriptor): void {
if (!!propertyDescriptor && !!propertyDescriptor.set) {
const original = propertyDescriptor.set;
propertyDescriptor.set = function(next) {
original.apply(this, [next !== null && next !== undefined && `${next}` !== 'false']);
}
} else {
coerceWithoutAccessors(target, key);
}
};
function coerceWithoutAccessors(target: any, key: string): void {
const getter = function() {
// using Typescript reflection
// @ts-ignore
return this['__' + key];
};
const setter = function(next: any) {
// using Typescript reflection
// @ts-ignore
this['__' + key] = next !== null && next !== undefined && `${next}` !== 'false';
};
Object.defineProperty(target, key, {
get: getter,
set: setter,
enumerable: true,
configurable: true
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment