【问题标题】:angular typescript declare generic with empty object [duplicate]角度打字稿用空对象声明通用[重复]
【发布时间】:2021-11-23 18:19:30
【问题描述】:

我正在尝试在 Angular 12 中声明以下变量

private subject = new BehaviorSubject<ApiResponse>({});

我得到错误

Argument of type '{}' is not assignable to parameter of type 'ApiResponse'
Type '{}' is missing the following properties from type 'ApiResponse'

类 ApiResponse 具有以下属性

export interface ApiResponse {
  success: boolean
  message: string
  exception: any
  totalRowCount: number
}

如果我明确声明每个属性,它可以正常工作 有没有办法在不显式声明每个属性的情况下声明一个空对象?

【问题讨论】:

    标签: angular


    【解决方案1】:

    ? 用于可选属性

    export interface ApiResponse {
      success?: boolean;
      message?: string;
      exception?: any;
      totalRowCount?: number;
    }
    

    【讨论】:

    • tsconfig 中是否有任何设置可用于允许空对象?
    • 无需更改任何配置@SudhirJangam
    【解决方案2】:

    使用ReplaySubject 而不是BehaviorSubject。在大多数情况下,您不想处理空对象,而响应尚未到来

    【讨论】:

      猜你喜欢
      • 2018-11-06
      • 1970-01-01
      • 2020-09-12
      • 2020-01-08
      • 2021-01-20
      • 1970-01-01
      • 2021-09-27
      • 2017-08-12
      • 1970-01-01
      相关资源
      最近更新 更多