0

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?

3
  • Are they classes or interfaces? Commented Apr 20, 2021 at 16:15
  • interfaces. As in export type Business = { id: string; name: string; ...} Commented Apr 20, 2021 at 16:16
  • 1
    You're looking for a custom Type Guard. Commented Apr 20, 2021 at 16:18

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome!! Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.