【问题标题】:StrictTemplates and union type in Interface接口中的严格模板和联合类型
【发布时间】:2021-04-05 11:21:43
【问题描述】:

我有这个界面

export interface User{
  name: string
  birthday: number | Timestamp
  ...
}

with strictTemplates:false 当我在 Timestamp 中获取带有生日的服务器数据以及将带有生日编号的数据放入本地 Store 时,我使用此接口。没有错误。 在 strictTemplates: true 我有这个错误:

Types of property 'birthday' are incompatible.
Type 'number | Timestamp' is not assignable to type 'number'.
  Type 'Timestamp' is not assignable to type 'number'.

这里的最佳做法是什么?我做了三个接口:

 //without birthday
export interface User{
  name: string
  ...
}

export interface UserFromFirestore extends User {
  birthday: Timestamp;
}
export interface UserInLocal extends User {
  birthday: number;
}

我的功能(伪代码)是:

getUser(id: string):Observable<UserInLocal>{
  this.getDataFromFirestore(id).pipe(
  map((user:UserFromFirestore) => userWithBirthdayInNumber(user)))
}

我可以做得更好,对吧?我的解决方案太冗长了吧?

【问题讨论】:

    标签: angular typescript google-cloud-firestore


    【解决方案1】:

    您可以在此处使用泛型。 更多信息:generics

    export interface User<T>{
      name: string
      birthday: T
    }
    
      obj1: User<number>;
      obj2: User<Timestamp>;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-27
      • 2019-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-21
      • 1970-01-01
      相关资源
      最近更新 更多