React Navigation with TypeScript: The specified type is incompatible with the 'BottomTabNavigatorConfig' parameter

I'm currently in the process of developing a mobile app using React Native and I've chosen to manage my navigation with React Navigation V2.

Recently, I came across some code on the official documentation that seemed perfect for what I needed:

const MainTabs = createBottomTabNavigator(
  { Home: HomeStack, Settings: SettingsStack },
  {
    navigationOptions: ({ navigation }: NavigationScreenProps) => ({
      tabBarIcon: ({ focused, tintColor }) => {
        const { routeName } = navigation.state;
        let iconName;
        if (routeName === "Home") {
          iconName = `ios-information-circle${focused ? "" : "-outline"}`;
        } else if (routeName === "Settings") {
          iconName = `ios-options${focused ? "" : "-outline}`;
        }

        // Feel free to customize with your preferred icon component
        return <Ionicons name={iconName} size={25} color={tintColor} />;
      }
    }),
    tabBarOptions: {
      activeTintColor: "tomato",
      inactiveTintColor: "gray"
    }
  }
)

However, I encountered an unexpected error when trying to implement this code in TypeScript:

[ts]
Argument of type '{ navigationOptions: ({ navigation }: any) => { tabBarIcon: ({ focused, tintColor }: { tintColor: string | null; focused: boolean; }) => Icon; }; }' is not assignable to parameter of type 'BottomTabNavigatorConfig'.
  Types of property 'navigationOptions' are incompatible.
    Type '({ navigation }: any) => { tabBarIcon: ({ focused, tintColor }: { tintColor: string | null; focused: boolean; }) => Icon; }' is not assignable to type 'NavigationBottomTabScreenOptions | ((navigationOptionsContainer: NavigationScreenConfigProps & { navigationOptions: NavigationScreenProp<NavigationRoute<NavigationParams>, NavigationParams>; }) => NavigationBottomTabScreenOptions) | undefined'.

I'm puzzled as to why this error is occurring. Can anyone provide insights into what might be causing this issue?

Answer №1

IMPORTANT: Please note that the options are set to {loginHeader as StackHeaderOptions}

const AuthStack = createStackNavigator()
export default () => (
   <AuthStack.Navigator screenOptions={navigationHeader}>
      <AuthStack.Screen name={Routes.LOGIN} component={Login} options={loginHeader as StackHeaderOptions} />
      <AuthStack.Screen name={Routes.CHAT.INFO} component={Info} />
      <AuthStack.Screen name={Routes.CHAT.FLOW} component={ChatFlow} />
   </AuthStack.Navigator>
)

const loginHeader = ({ navigation }) => ({
   title: 'Login',
   headerRight: () => (
       <HeaderButton
          imageSource={IMG_INFO}
          onPress={() => navigation.navigate('Info')}
       />
   )
}) 

Answer №2

It's important to consider the expectations of the prop when passing it, as you may need to perform a casting in the expression. For example:

navigationOptions: ({ navigation as any }: any)

Answer №3

In my personal experience, I have encountered issues with react-navigation when it comes to the navigationOptions property types. The key solution here is to be extremely specific about the types you are using.

Upon closer examination, it appears that the weak point lies in the argument type for the tabBarIcon function. To address this, add a clear type to the unpacked argument:

...
  tabBarIcon: ({ focused, tintColor }:TabBarIconProps) => {
...

It should automatically derive the return type.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Uploading raw data to Firebase bucket

I am currently developing a nodejs/typescript application that leverages Firebase Functions, and I am facing a challenge with uploading a JSON object to a bucket. The issue arises from the fact that the JSON data is stored in memory and not as an actual fi ...

What is the process for obtaining the feedback from a new StepFunctionsStartExecution operation using AWS CDK?

Task Explanation: Iterate through the children in Step Function 1 Forward each JSON object to Step Function 2 Upon completion of Step Function 2, a response is obtained from an external API Utilize this API response within Step Function 1 Visual Represen ...

Understanding the mechanics of async/await and Promise in TypeScript

Trying to wrap my head around how async, await, and promises work with this simple function. function delay(ms: number) { return new Promise<void>(function(resolve) { setTimeout(resolve, ms); }); } async function asyncAwait() { c ...

I am unable to utilize the Web Share API for sharing a file within my React app written in TypeScript

Trying to launch a WebApp for sharing files has been quite a challenge. After some thorough research, I stumbled upon the Web Share API which seemed like the perfect solution based on standard practices. The documentation provided a clear outline of how it ...

Using node.js to set the billing address while confirming a Stripe Payment intent

Is there a way to specify the billing address of a payment intent with Node.js? When using the Stripe.js browser-side framework, I can easily accomplish this by utilizing Stripe elements and the stripe.confirmPayment function, which automatically captures ...

What is the best practice for making a gRPC call within a Typescript Vue.Js component?

Upon reviewing the grpc documentation, I discovered that proto files can be used to generate Node (Javascript), Typescript with the assistance of grpc_tools_node_protoc_ts, and grpc-web. Given that performance is not a critical factor in my particular situ ...

What is the best way to transfer props between components using typescript?

I have a unique button component that I need to include in another component. The button type and interface I am using are as follows: type IButton = { className?: string, onClick?: MouseEventHandler; children: React.ReactNode; props: IButt ...

Managing input and output using a collaborative service

I've been working on refactoring some code that contains a significant amount of duplicate methods between two components. Component A is a child of component B, and they can be separate instances as intended. The issue I'm facing revolves around ...

Tips on providing validation for either " _ " or " . " (select one) in an Angular application

I need to verify the username based on the following criteria: Only accept alphanumeric characters Allow either "_" or "." (but not both) This is the code snippet I am currently using: <input type="text" class="form-control" [ ...

Is there a way to incorporate my getter into a computed property?

My Vuex Store is built using Vuex module decorators and I am facing an issue with using a getter for a computed property. Here is my code: @Module export default class WorkoutModule extends VuexModule { _workout: Workout; @Mutation startWork ...

Utilize an external JavaScript function within a React and TypeScript document

I have encountered an issue in my React/Next.js/TypeScript file where I am trying to load the YouTube iframe API in my useEffect hook. Here is the code snippet: useEffect(() => { const tag = document.createElement('script'); tag.src = ...

Exploring the capabilities of the Next.js router and the useRouter

import { routeHandler } from "next/client"; import { useRouteNavigator } from "next/router"; const CustomComponent = () => { const routerFromHook = useRouteNavigator(); } export default CustomComponent; Can you explain the disti ...

The function successfully triggers when clicked using (React, JS, TS) but does not respond to key presses

When the function is called with "onClick", it works correctly, but when called with "onKeyPress", it does not execute an if statement. scenario Consider a scenario where you can search for food recipes (e.g. "pizza") and receive a list of recipes from a ...

Solving the error message "Cannot find module '@angular/router/src/utils/collection' or its corresponding type declaration"

How do I troubleshoot this Error: src/app/metronic/orderByLocation/locationsByOneOrder/locationsByOneOrder.component.ts:7:25 - error TS2307: Cannot find module '@angular/router/src/utils/collection' or its corresponding type declarations.m 7 imp ...

How can you use console.log() effectively in an Angular application?

While debugging an Angular project, I have encountered a situation where console.log() does not seem to be working properly despite ensuring that all logging levels are enabled in the Chrome console settings. I have tried placing the console.log() statemen ...

The parameter 'CallHistoryMethodAction<[string, unknown?]>' does not match the 'UserActionType' parameter

Using a development environment with React, TypeScript, and connected-react-router. My Intention: I aim to utilize the router action asynchronously within the user action. After successful login, I want the application to navigate to the main screen. Err ...

What is a Generic Type in an Array?

Currently, I'm working on designing a mockup app that displays data in the form of buttons in a list. I have successfully implemented most of the features but I have encountered a problem. I have initialized an array and another class to manage the da ...

What is the best way to connect a JSON object with a variable in TypeScript Angular 2?

I have a single json file that I need to connect with a variable in order to display it on the user interface. testjson= {"date":1468497879354,"faulty":"F-3","mileage":"150,900 mls","search":[]} Also, in the HTML code: <div> <span>{{ test ...

Auto scrolling in React Native Flatlist

I'm working on a FlatList component that I want to automatically scroll. Below is the current code: <FlatList contentContainerStyle={{}} data={banners} renderItem={(item) => ( <Image source={{ uri: item.item ...

Discovering the parameter unions in Typescript has revolutionized the way

My current interface features overloaded functions in a specific format: export interface IEvents { method(): boolean; on(name: 'eventName1', listener: (obj: SomeType) => void): void; on(name: 'eventName2', listener: (obj: Som ...