我有以下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 个解决方案,但对我来说还不够满意...
我可以在任何位置写字
(entry as IHistory).timeStamp
我可以定义例如
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/