javascript - Throw error if config object doesn't contain all required properties -


i have es6 class require config object. if property missing, i'd throw error.

the solution if found keep code short , not add if(!object.propn)... every property :

class myclass {   constructor(config) {     if (!config) {       throw new error("you must provide config object");     }      this.prop1 = config.prop1;     this.prop2 = config.prop2;     this.prop3 = config.prop3;     this.prop4 = config.prop4;      (const key in this) {       if (!this[key]) {         throw new error(`config object miss property ${key}`);       }     }    } } 

is ok in javascript ?

for configs, use feature destructuring assignment check whether properties in object or not using sugar of es6 (es2015).

and furthermore, can set default values configs feature.

{prop1, prop2, prop3: path='', prop4='helloworld', ...others} = config 

after destructuring assignment has been done, need check before going specific config. i.e.

if (!prop1) {   throw new error(`config object miss property ${prop1}`); } dosomething(prop1); 

but if still want check configs @ beginning, can this,

class myclass {   constructor(config) {     if (!config) {       throw new error("you must provide config object");     }      // can assign values new object "tmpconfig" or assign them "config" case config.propx === undefined     ({prop1: config.prop1=undefined, prop2: config.prop2=undefined, prop3: config.prop3=undefined, prop4: config.prop4=undefined} = config);      (const key in config) {       if (!config[key]) {         throw new error(`config object miss property ${key}`);       }     }      object.assign(this, config);   } } 

or using object.assign() setting default values,

class myclass {   constructor(config) {     if (!config) {       throw new error("you must provide config object");     }      let requiredconfigs = {       prop1: undefined,       prop2: undefined,       prop3: undefined,       prop4: undefined,     }     let tmpconfig = object.assign(requiredconfigs, config);      (const key in tmpconfig) {       if (!tmpconfig[key]) {         throw new error(`config object miss property ${key}`);       }     }      object.assign(this, tmpconfig);   } } 

=> we use destructuring assignment , object.assign() lot doing setting configs things.


Comments

Popular posts from this blog

javascript - Laravel datatable invalid JSON response -

java - Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; -

sql server 2008 - My Sql Code Get An Error Of Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the varchar value '8:45 AM' to data type int -