Search code examples
angulartypescriptangular11

How to set a variable type but without giving it a value?


On and Angular 11 project using Typescript with Strict Mode I have:

export class AvatarComponent { 
  @Input() user: UserModel = null;
}

I am getting the compilation error:

Type 'null' is not assignable to type 'UserModel'.

Where UserModel is:

export class UserModel {
  id?: number;
  name?: string;
}

How can I set user variable type to UserModel but with null value?


Solution

  • If you desire to set null:

    export class AvatarComponent { 
      @Input() user: UserModel | null = null;
    }
    

    If you desire to set undefined:

    export class AvatarComponent { 
      @Input() user: UserModel;
    }