【问题标题】:How to set a variable type but without giving it a value?如何设置变量类型但不给它一个值?
【发布时间】:2021-03-07 00:45:13
【问题描述】:

我有使用 Typescript 和严格模式的 Angular 11 项目:

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

我收到编译错误:

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

UserModel 在哪里:

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

如何将user 变量类型设置为UserModel 但值为空?

【问题讨论】:

  • 尝试new UserModel() id 和 name 将为空
  • 将类型设为UserModel | null?
  • 顺便说一句,UserModel 是一个类而不是类型。是的,@R.Richards 是正确的
  • @Input() user: UserModel; 有什么问题 - 为什么需要将其显式设置为 null,而默认情况下它是 undefined?跨度>

标签: angular typescript angular11


【解决方案1】:

我相信会这样

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

https://stackblitz.com/edit/angular-ivy-7f6obj?file=src%2Fapp%2Fapp.component.ts

【讨论】:

    【解决方案2】:

    如果你想设置null:

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

    如果你想设置undefined:

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

    【讨论】:

    • 我之前尝试将其设置为未定义,但收到错误“属性'用户'没有初始化程序并且未在构造函数中明确分配。”。我还将构造函数添加到类 UserModel 但没有解决它。我错过了什么吗?
    • 试试@Input() 用户:UserModel = undefined;
    猜你喜欢
    • 2019-04-03
    • 2019-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多