Angular - Type undefined is not assignable to type 'T'

Viewed 16209

I am trying to use this google dynamic form for Angular 11 as is and I get errors.

Here is all the code copied verbatim, obviously it works here but is giving me errors on my dev machine. https://stackblitz.com/edit/angular-sccsnu?file=src%2Fapp%2Fquestion-base.ts

√ Compiled successfully.

Error: src/app/_models/question-base.ts:21:5 - error TS2322: Type 'T | undefined' is not assignable to type 'T'.
  'T' could be instantiated with an arbitrary type which could be unrelated to 'T | undefined'.
    Type 'undefined' is not assignable to type 'T'.
      'T' could be instantiated with an arbitrary type which could be unrelated to 'undefined'.

21     this.value = options.value;
       ~~~~~~~~~~
3 Answers

Adding ! to ‘this.value = options.value!;’ should fix it because ‘!’ operator indicate this value isn’t nullable.

You can get rid of all the errors of "Type 'T | undefined' is not assignable to type 'T'" by setting the property "strict" in tsconfig.json file to false

Consider the type of options

   options: {
      value?: T;
  }

So options.value will be of type T | undefined because of the ? that implies value is optional

Now the type of this.value

  value: T;

So this.value will be of type T

Now lets say we do not provide any value for options.value then we will be assigning this.value = undefined which should ideally warn us as this.value is of type T

In short the solution is either to remove the optional parameter ? or to change the type of this.value

value: T | undefined
Related