In React Native, I have a component that accepts an item prop. It can be of either type Business or Product. a Business object has a name prop, but Product doesn't.
If I define item TS as Business | Product, I can only access props that are common for both definitions. I want to check if I have item.name but it's giving me Property 'name' does not exist on type 'Business | Product'
What's the correct way of doing this?
1 Answer
The best way is to create a custom type guard. For example:
function isBusiness(item: Business | Product): item is Business {
return (item as Business).name !== undefined;
}
When you will use this isBusiness function inside a if statement, Typescript will know that item is of type Business if true or Product if false.
1 Comment
Ben
Awesome!! Thank you.
export type Business = { id: string; name: string; ...}