Search code examples
typescripttsconfig

How to use stringPropertyInitialization with Object.assign in Typescript


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:

  1. specify default values (objects can be really large)
  2. use doSomething: boolean = {} as any;
  3. assign value in constructor outside the data property because there can be a lot of parameters and calling constructor would become too ugly for my taste
  4. Make doSomething accept undefined values

Solution

  • One 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);
        }
    }