When writing plain Javascript, i often build classes with a "config" property, whose keys have some default values, for example:
class MyClass{
config = {
someProp:true,
otherProp:5
}
constructor(config){
for(let prop in config){
this.config[prop] = config[prop]
}
}
}
This is very convenient, because i can just loop through the passed object and override defaults(if a value is provided)
In Typescript, i tried something like this:
class MyClass{
config = {
someProp:true,
otherProp:5
}
constructor(config?: { someProp?: boolean,otherProp?:number }) {
if (config) {
for (let prop in config) {
this.config[prop] = config[prop]
}
}
}
}
I get the following error:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ someProp: boolean; otherProp: number; }'. No index signature with a parameter of type 'string' was found on type '{ someProp: boolean; otherProp: number; }'.
I understand more or less the meaning of this error, but i guess my whole approach here is very "JS-like", and should be changed.
What would be the conventional, simple way to do this in Typescript? The idea is to quickly merge the provided properties, with the default ones, without repeating various checks.