Search code examples
javascripttypescriptreact-nativereact-typescript

What is the correct type of props to replace any?


I have this current App function originally in js which I would like to change to Typescript:

export default function App(props: any): JSX.Element {
  console.log(`props: ${props.studentList}`);
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="React Native">
        <Stack.Screen
          name="React Native"
          component={HomeScreen}
          initialParams={{studentList: props.studentList}}
        />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

a sample of props would be:

props= { studentlist: [{"name":"Jonh", "course":"Typescript"},{"name":"Jane","course":"Javascript"}]}

What would be the way to replace any?

Thank you


Solution

  • You would need to define types for your props, BEFORE the function:

    type Student = {
      name: string;
      course: string;
    };
    
    type AppProps = {
      studentList: Student[];
    };
    

    Then, first declare the Stack and then the functional as a functional component:

    const Stack = createStackNavigator();
    
    const App: React.FC<AppProps> = ({ studentList }: AppProps) => {
      console.log(`props: ${studentList}`);
    
      return (
        <NavigationContainer>
          <Stack.Navigator initialRouteName="React Native">
            <Stack.Screen
              name="React Native"
              component={HomeScreen}
              initialParams={{ studentList }}
            />
          </Stack.Navigator>
        </NavigationContainer>
      );
    };