angulartypescriptstrict

Angular 11 any/undefined types warnings


I upgraded my app from Angular v10 to v11 and now I get multiple errors and warnings because some (maybe all) fields can be undefined in a time:

for example:

const savedToken = new Token(JSON.parse(localStorage.getItem(AuthInterceptor.tokenKey)));

must become:

const savedToken = new Token(JSON.parse(<string>localStorage.getItem(AuthInterceptor.tokenKey)));

warning:

Argument of type 'string | null' is not assignable to parameter of type 'string'. 
Type 'null' is not assignable to type 'string' 
// I know the localStorage value can be null in this case.

another example:

public user$: Observable<User>;
// Property 'user$' has no initializer and is not definitely assigned in the constructor.

because the user$ is initialized in ngOnInit() as this.user$ = this.store.pipe()...

How did you solve it?

Even if I deactivate strict from angular.json, the result is same:

"@schematics/angular:application": {
    "strict": false
}

I really need to update all my app code line by line to angular 11? thanks


Solution

  • This is caused by TypeScript's Strict Class Initialization.

    https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#strict-class-initialization

    Solution 1

    Utilize the prop!: Type syntax as indicated by the TypeScript documentation to indicate to the compiler that we are aware that the prop has not been initialized and we will handle it later.

    @Component({...})
    export class ExampleComponent {
     @Input() inputExampleProp!: string; // ! indicates that we know the variable may be undefined
    }
    

    Alternate Solution

    If you do not care about strict class initialization, you can disable the feature completely in your tsconfig.json by adding a flag to your compiler options

    {
     "compilerOptions": {
        "strictPropertyInitialization": false
      }
    }
    

    Note: You may have to restart your IDE for the compilerOptions to refresh.