I am currently in the process of converting come legacy code into typescript for a project. The project contains a number of custom classes written in pure javascript which follow the same pattern of having a constructor which takes in a config object which can have many configuration options defined within it.
I've been toying with how to define the allowed config properties in typescript and haven't yet come up with a solution I'm entirely happy with. I started by declaring an interface for the config, which allows me to define the config options available but doesn't help with defaulting them - I have to copy my config interface twice or more for both the definition and the initialisation. What I (think I) want is to use object destrcuturing to define the class members once with default values and not have to worry about it after that e.g:
export interface MyClassConfig {
propA: string;
propB: boolean;
}
export class MyClass {
private propA: string = 'defautValue';
private propB: boolean;
constructor (config: MyClassConfig) {
{ propA, propB } = config;
}
}
Which could then be initialised with something like:
let mc = new MyClass({ propB: false }); //mc.propA == 'defaultValue', mc.propB === false
I don't like that this requires me to copy the property names multiple times though. Can anyone suggest a nice clean way to achieve this?