So I've been reading to the answers to this question and I haven't found one that works easily with extended classes, so I came up with this.
First you create a function that checks if an object has the properties of another object:
function checkValues(values = {}, targets) {
values = Object.keys(values);
targets = Object.keys(targets);
return values.every(keyValor => targets.includes(keyValor));
}
Then in a class you define the default values like this:
class Error {
constructor(options = {}) {
//Define default values
var values = {
title: '',
status: 500,
mesagge: ''
};
//Check if options has properties of values
var valid = checkValues(values, options);
//If options doesn't has all the properties of values, assign default values to options
if (!valid) {
options = valores
}
//Asign options to the class
Object.assign(this, options);
}
}
So now, if you want to have a child class you just need to declare the default values for that child class:
class FormError extends Error{
constructor (options = {}){
var values = {
invalidParams: [{name:'', reason: ''}]
};
var valid = checkValues(values, options);
if (!valid) { options = values}
super(options);
Object.assign(this, options);
}
}
EXAMPLE:
var a = new Error();
var b = new FormError();
var c = new FormError({invalidParams: [{name: 'User', reason: 'It has to be a string!'}]});
console.log(a, b, c);
Note: It only works if you want to have ALL the defaults values and not just some of them, for example:
var e = new Error({message: 'This is an error'});
console.log(e.message);// ''
//Error e will only have the default values, and message would be empty.
var h = new FormError({title: 'FORM ERROR', status: 400});
console.log(h.title);//''
//Error h will only have the defaults because I didn't provide 'invalidParams'