I've encountered a challenge while creating a function that interacts with database objects. In this case, I have two different data structures where the same property is named differently. Unfortunately, I cannot change these names and must find a solution using JavaScript.
Although there are additional variations between the objects, they are not relevant to the specific function at hand.
My goal is to utilize the same function for handling both types of objects. Below is a snippet demonstrating the issue:
interface TypeA {
itemName: string;
}
interface TypeB {
itemTitle: string;
}
function getItemName(item: TypeA | TypeB): string {
let name = '';
if (item.hasOwnProperty('itemName')) {
name = item.itemName;
} else {
name = item.itemTitle;
}
return name;
}
While the code functions as intended, my IDE highlights errors on the lines name = item.itemName;
and name = item.itemTitle;
, stating "Property does not exist on type" due to the lack of both properties in each object type.
What would be the correct approach in TypeScript to address this dilemma?