Reputation: 47058
I'm wondering if there is a more efficient / more compact way to do this. I have a configuration class instance where all the state is optional. It looks like this. I have a constructor like this (StoreConfig is pasted below):
constructor(config?:StoreConfig) {
config = config ? config : new StoreConfig();
}
Now just use the config with the default value getters.
/**
* Store configuration.
*/
export class StoreConfig {
static ID_KEY_DEFAULT:string = 'id';
static GUID_KEY_DEFAULT:string = 'gid';
constructor(private _idKey?:string, private _guidKey?:string) {};
get idKey():string {
return this._idKey ? this._idKey : StoreConfig.ID_KEY_DEFAULT;
}
get guidKey():string {
return this.guidKey ? this.guidKey : StoreConfig.GUID_KEY_DEFAULT;
}
}
Upvotes: 0
Views: 523
Reputation: 47058
This ended up working pretty well for the general design I was going for:
export const STORE_CONFIG_DEFAULT: StoreConfig = {
idKey: "id",
guidKey: "gid"
};
Object.freeze(STORE_CONFIG_DEFAULT);
export class StoreConfig {
public idKey: string;
public guidKey: string;
constructor(c?: Partial<StoreConfig>) {
let config = Object.assign({ ...STORE_CONFIG_DEFAULT }, c);
this.idKey = config.idKey;
this.guidKey = config.guidKey;
}
}
Some other classes can now rely on STORE_CONFIG_DEFAULT for the default configuration.
Upvotes: 0
Reputation: 2634
Use a default value for your constructor arguments, like so:
export class StoreConfig {
constructor(
private _idKey: string = "id",
private _guidKey: string = "gid"
) {}
get idKey(): string {
return this._idKey
}
get guidKey(): string {
return this._guidKey
}
}
by providing a default value you're letting Typescript know this is an optional argument that falls back to its default value.
then it doesn't complain about missing arguments when you do this:
const x = new StoreConfig()
Upvotes: 1