Created
October 3, 2021 10:51
-
-
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
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
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