Home > Back-end >  Select types conditionally
Select types conditionally

Time:02-04

I have a monorepo with two apps: client and merchant. They share a common stack navigator - authentication, which is nested inside the root navigator. To set screen props for the authentication navigator, I need to use the root navigator, which is specific for each app. Also, to avoid duplicates, the authentication navigator, types, and screens are in a package. In one of the screens I have export const RequestEmailLinkScreen = ({ route, navigation }: Props) => { But the question here is how to load the correct Props (clent vs merchant) based on the app used? I do have const appSlug = Constants.expoConfig?.slug; So I was thinking to do something like this:

import { MyScreenProps as ClientMyScreenProps } from '../../../types/client';
import { MyScreenProps as MerchantMyScreenProps} from '../../../types/merchant';

const appSlug = Constants.expoConfig?.slug;

type Props = appSlug === "client" ? ClientMyScreenProps : MerchantMyScreenProps;

export const MyScreen = ({ route, navigation }: Props) => {

But this is not right. How do I do that and can you think of a better way?

CodePudding user response:

If I understood you correctly, you are trying to get a compile time value (the type) with a runtime value (the slug).

I'm afraid this is not possible with your current code.

I suggest you accept both Props and resolve the app during runtime. For example:

import { MyScreenProps as ClientMyScreenProps } from '../../../types/client';
import { MyScreenProps as MerchantMyScreenProps} from '../../../types/merchant';

const appSlug = Constants.expoConfig?.slug; // Btw, you could also have an `undefined` here, take care of this
export const MyScreen = ({ route, navigation }: ClientMyScreenProps | MerchantMyScreenProps) => {
  if (appSlug === 'client') {
    // Do whatever you need on the client app
  } else {
    // Do whatever you need on the non-client app
  }
}

This, of course, means that you won't have typing assistance as, as I stated, you can't use a runtime value during compile time.

No matter what I think, it always depends on you doing a final runtime check to choose a path or another... If you really want to be able to run code as either one or another, you can always split the function in two and place a little code differentiating them both at the beginning. Take a look at this playground to see what I mean.

  • Related