#How to use the Record utility type, with custom type for each index

5 messages · Page 1 of 1 (latest)

ivory wind
#

hey people! I'm trying to create a specific type that will return a type based on the enum name. Tbh I'm not sure if it's possible.

export enum AppScreens {
  HomeScreen = "HomeScreen",
  SettingsScreen = "SettingsScreen",
}

export type RootStackParamList = Record<
  AppScreens,
  AppScreens extends AppScreens.HomeScreen
    ? { screen: string; params: { sort: string } }
    : undefined
>;

======== result type

type RootStackParamList = {
    HomeScreen: undefined; <===== { screen: string; params: { sort: string } } how can I achieve this?
    SettingsScreen: undefined;
}
steady sonnet
#

Why not just use an interface?

ivory wind
#

in this particular case, I'm not sure if this will make diff... and React Navigation recommend to use types

#

but I think that I found a solution

#
export type RootStackParamList = {
  [K in AppScreens]: K extends AppScreens.HomeScreen
    ? { screen: string; params: { sort: string } } | undefined
    : undefined;
};

result

type RootStackParamList = {
    HomeScreen: {
        screen: string;
        params: {
            sort: string;
        };
    } | undefined;
    SettingsScreen: undefined;
}