TypeScript: use two different types

Thanks for your reply @luisherranz

I don’t believe you can find a perfect solution to this problem.

Actually, the type guard inside the data prop is not a good thing either, because it will still fail in strict mode:
in your example, if the isProductionArchive function returns false, then the value passed to the data prop is false, which is not of type ProductArchiveData, and is not desired in any case. It would be acceptable ONLY if we were sure that the component will not be rendered if the value is false, But to make it work with typescript in strict mode we would neet to type the data prop as ProductArchiveData | false and then add some conditional logic inside the component:

const Shop: React.FC<{ data: ProductArchiveData | false }> = ({ data }) => {
  if (!data) {
    return null;
  }

  // ...
};

This is far from perfect. Also, there is no reason to do such a thing outside of the Switch, so it kind of makes the Shop component aware that it’s going to be used inside the Switch - which again is not good.
My solution with the Case component and typecasting is still the cleanest one I could think of. The component being used inside the Case does not need to “know” it’s being used that way, it accepts a certain type of props and inside the Case we are sure the data IS of the correct type so this is what typecasting is for, when there is no way for typescript to know it, but we know it :slight_smile:

Agreed!

If you are willing to contribute it to the code I’ll be more than glad to merge the PR :slightly_smiling_face: