繁体   English   中英

打字稿类型 a 或类型 b

[英]Typescript type a or type b

我有以下 2 个接口

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;

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

如果在每个接口中添加特定的定义,则可以将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

  }
})

另一种可能性是使用用户定义的类型防护,即帮助编译器得出参数是否具有特定类型的函数。 以下代码应解决您的特定问题-我在已更改的位中添加了注释。

interface IComment extends IData {
    comment: string;
}

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

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

const data: Array<IHistory | IComment> = [];

data.map((entry: IHistory | IComment) => {
    // Explicitely narrows down the type to IHistory within the block
    if (isHistory(entry)) {
        // entry.timeStamp
    } else {
        // entry.comment
    }
});

// User-Defined Type Guard
function isHistory(data: IData): data is IHistory {
    return data.isHistory;
}

有关更多信息,请参见用户定义类型防护中的 高级类型

在这种情况下,您可以使用“in”。

if('timeStamp' in entry) {
    entry.timeStamp 
} else {
    entry.comment
  }

文档: https : //www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-differentiating-types

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM