Last active
June 3, 2022 19:30
-
-
Save bolencki13/41226f2436f6e6c7c69130f2f963e30e to your computer and use it in GitHub Desktop.
The purpose of this decorator is to re-assign the default value when the incoming value is null or undefined.
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
/** | |
* The purpose of this decorator is to re-assign the default value when the incoming value is null or undefined. | |
* This can be modified to ignore null or undefined as an incoming value. | |
*/ | |
type UseDefaultOptions = { | |
whenNull?: boolean; | |
whenUndefined?: boolean; | |
}; | |
/** | |
* Apply the default property value when the proposed new value is not valid | |
* @param options options to determine when the default property value should be re-applied | |
* @returns | |
*/ | |
export function UseDefault(options: UseDefaultOptions = { whenNull: true, whenUndefined: true }) { | |
return function (target: any, propertyKey: string) { | |
const instance = new target.constructor(); | |
let defaultValue = instance[propertyKey]; | |
const pattern: any = { | |
get() { | |
return this[`_${propertyKey}`]; | |
}, | |
set(newValue: any) { | |
if (options.whenNull && newValue === null) { | |
this[`_${propertyKey}`] = defaultValue; | |
} else if (options.whenUndefined && newValue === undefined) { | |
this[`_${propertyKey}`] = defaultValue; | |
} else { | |
this[`_${propertyKey}`] = newValue; | |
} | |
}, | |
}; | |
Object.defineProperty(target, propertyKey, pattern); | |
}; | |
} | |
// Example | |
class MyTest { | |
@UseDefault() | |
foo: string = 'bar' | |
} | |
const instance = new MyTest() | |
console.log(instance.foo) // bar | |
instance.foo = null | |
console.log(instance.foo) // bar | |
instance.foo = undefined | |
console.log(instance.foo) // bar | |
instance.foo = 'hello world' | |
console.log(instance.foo) // hello world |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment