Skip to content

Instantly share code, notes, and snippets.

@alaindet
Created July 13, 2020 16:38
Show Gist options
  • Save alaindet/bd31154be9b5634aa58a12226a7177c6 to your computer and use it in GitHub Desktop.
Save alaindet/bd31154be9b5634aa58a12226a7177c6 to your computer and use it in GitHub Desktop.
const toBoolean = (context: any, flags: string[]) => {
for (const flag of flags) {
const propValue = context[flag];
const propType = typeof propValue;
if ('boolean' === propType) {
context[flag] = propValue;
}
else if ('string' == propType) {
if (propValue === 'false' || propValue === 'no') {
context[flag] = false;
} else {
context[flag] = true;
}
}
else {
context[flag] = !!propValue;
}
}
};
interface ICommon {
booleanish: string | boolean;
}
class MyClass {
flag: ICommon['booleanish'];
constructor(flag: ICommon['booleanish']) {
this.flag = flag;
toBoolean(this, ['flag']);
}
}
const obj = new MyClass('no');
console.log(obj.flag);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment