I have a class like
export class Config{
public doSomething: boolean;
public doSomethingOptionally?: boolean
constructor(data: {
doSomething: boolean,
doSomethingOptionally?: boolean
}) {
Object.assign(this, data);
}
}
Passing data to constructor this way is really easy and IntelliSense is smart enough to not allow developers creating new instance of Config
class without specifying doSomething
property, but it does without doSomethingOptionally
.
All this works great, but as soon as I enable strictPropertyInitialization
in tsconfig.json
I get a bunch of errors because doSomething
was not initialized.
What is the best workaround for this?
I don't want to:
doSomething: boolean = {} as any;
data
property because there can be a lot of parameters and calling constructor would become too ugly for my tastedoSomething
accept undefined valuesOne solution is to let the compiler know what properties are initialized via Object.assign
using the definite assignment assertion
export class Config{
public doSomething!: boolean;
public doSomethingOptionally?: boolean
constructor(data: {
doSomething: boolean,
doSomethingOptionally?: boolean
}) {
Object.assign(this, data);
}
}