Type for params for a navigate function

34 views Asked by At

Hi can anyone help me on this Typescript, recently moved to it, try reading documents and chatGPT for it but still have some problems.

Thing is I have two enums that contains screen key

export enum OnboardFlowScreens {
  ONBOARDING = "Onboarding",
  WELCOME = "Welcome",
}

export enum AuthFlowScreens {
  SIGNUP = "SignUp",
  LOGIN = "Login",
}

type BaseParamList = {
  [K in ScreenName]: any;
};

export interface OnboardFlowParamList extends AbstractParamList {
  [OnboardFlowScreens.ONBOARDING]: undefined;
  [OnboardFlowScreens.WELCOME]: { user: string };
}

export interface AuthFlowParamList extends AbstractParamList {
  [AuthFlowScreens.SIGNUP]: { user: string };
  [AuthFlowScreens.LOGIN]: { usrLogin: string };
}

type Merge<T> = {
  [K in keyof T]: T[K];
};

export interface AnyParamList
  extends Merge<
    OnboardFlowParamList &
      AuthFlowParamList
  > {}

I tried to create a custom navigate function, i'm not using the default one from react-navigation

const navigate = <T extends keyof AnyParamList>(
  screen: T,
  params?: AnyParamList[T]
): void => {
  const props = [screen, params] as never;
  navigationRef.current?.navigate(...props);
};

When I use this navigate function like below for example, the type for it is const navigate: <OnboardFlowScreens.WELCOME>(screen: OnboardFlowScreens.WELCOME, params: any) => void How can I change params: any to params: {user: 'string'} at here, or exactly AnyParamList[screen] as I defined

navigate(OnboardFlowScreens.ONBOARDING, "a"); should be invalid here
1

There are 1 answers

1
Solar1407 On

Made it working through update BaseParamList

type BaseParamList = {
  [K in ScreenName]: {} | undefined;
};