typescript 类型 a 或类型 b

标签 typescript

我有以下2个接口(interface)

interface IComment extends IData {
  comment: string;
}
interface IHistory extends IData{
  differences: any[];
  timeStamp: number;
}

两者都延伸

interface IData {
  user: string;
  date: Moment | string;
  isHistory: boolean;
}

现在解决问题

我有一个包含 IComment 和 IHistory 元素的数组。

const data: Array<IHistory | IComment> = [...someHistoryArray, ...someCommentArray]

现在,当我想映射数组并访问时间戳时

data.map((entry: IHistory | IComment) => {
  if(entry.isHistory) {
    entry.timeStamp 
    // TS2339: Property 'timeStamp' does not exist on type 'IHistory | IComment'. Property 'differences' does not exist on type 'IComment'.
  } else {
    entry.comment
    // TS2339: Property 'comment' does not exist on type 'IHistory | IComment'.   Property 'comment' does not exist on type 'IHistory'.
  }
})

好吧,我找到了 2 个解决方案,但对我来说还不够满意...

  1. 我可以在任何位置写字

    (entry as IHistory).timeStamp 
    
  2. 我可以定义例如

    const historyEntry: IHistory = entry as IHistory;
    

还有其他可能的解决方案吗?

最佳答案

如果在每个接口(interface)中添加特定定义,则可以使用 isHistory 作为并集的判别式:

interface IComment extends IData {
    comment: string;
    isHistory: false;
}
interface IHistory extends IData {
    differences: any[];
    timeStamp: number;
    isHistory: true;
}
interface IData {
    user: string;
    date:  string;
    isHistory: boolean;
}

let data: Array<IComment | IHistory>=[]
data.map((entry: IHistory | IComment) => {
  if(entry.isHistory === true) {
    entry.timeStamp //ok 

  } else {
    entry.comment //ok

  }
})

关于 typescript 类型 a 或类型 b,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54823932/

相关文章:

angular - 无法从 'sockjs-client' 导入( typescript )

javascript - 修改 typescript 文件时,Angular2 在浏览器中没有变化

Angular 6 - 一个输入中的更改值更改多个输入中的值

javascript - RxJS5: .combineLatest() 有投影功能?

Angular 5 : Function calls are not supported in decorators

c# - 在 Angular 2 和 ASP.NET Core 中使用相对图像路径

javascript - typescript 。引用错误 : require is not defined

node.js - 在 Angular 5 中,如何导入没有 @types 的 NPM 模块

typescript - 我可以有 `super` 或这个,但不能两者都有?

Angular 5 : Iterate Over Enum Using *ngFor