I am currently working with two interfaces:
interface IComment extends IData {
comment: string;
}
interface IHistory extends IData{
differences: any[];
timeStamp: number;
}
Both of these interfaces extend another interface:
interface IData {
user: string;
date: Moment | string;
isHistory: boolean;
}
Now, the issue arises when dealing with an array containing elements of both IComment and IHistory.
const data: Array<IHistory | IComment> = [...someHistoryArray, ...someCommentArray]
When trying to map over this array and access the timeStamp property, errors occur due to TypeScript not recognizing the specific types.
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'.
}
})
I have found two potential solutions, but they are not entirely satisfactory to me...
I could manually cast the entry at each instance:
(entry as IHistory).timeStamp
Alternatively, I could create a new variable with the correct type:
const historyEntry: IHistory = entry as IHistory;
Are there any other possible solutions that could address this issue effectively?