What is the process for specifying the type of router in typescript?

I am currently working with a router array and I would appreciate some TypeScript tips when adding route items. Currently, I am receiving tips on addition but encountering an error when using props.navigate. The component shows an error if not set as any.

Can someone assist me with the TypeScript for this?

Here is my code:

// types.ts
import { StackNavigationProp, StackNavigationState, ParamListBase } from ‘@react-navigation/stack’;
import { RouteProp, StackNavigationOptions, StackNavvigationEventMap } from '@react-navigation/native';

type RootStackParamList = {
  Home: undefined;
  Profile: { userId: string };
  Settings: undefined;
};

export type INavigationType<T extends keyof RootStackParamList> = 
  StackNavigationProp<RootStackParamList, T>;
  
export type IRouteType<T extends keyof RootStackParamList> =
  RouteProp<RootStackParamList, T>;
  
export type IStackRouteType = 
  RouteConfig<
    RootStackParamList,
    keyof RootStackParamList ,
    StackNavigationState<ParamListBase>,
    StackNavigationOptions,
    StackNavvigationEventMap
  >

// index.tsx
import { createStackNavigator } from '@react-navigation/stack';
import { IStackRouteType } from './types;'


const StackNavigator = createStackNavigator<RootStackParamList>();

const stackRoutes: IStackRouteType= [
  {
    name: 'Home',
    component: HomeScreen,
    options: {
      headerShown: false
    }
  },
  {
    name: 'Profile',
    component: ProfileScreen,  // <----- error
    options: {
      headerShown: false
    },
    listeners: () => {
       return ({
         state: (e) => {
            console.log('state changed', e.data);
         }, 
       })
    }
  },
   {
    name: 'Settings',
    component: Settings,
    options: {
      headerShown: false
    }
  },
];

export default function App() {
  return (
    <NavigationContainer>
      <StackNavigator.Navigator>
        {stackRoutes.map((route, index) => (
          <StackNavigator.Screen
            key={route.name}
            {...route}
          />
        ))}
      </StackNavigator.Navigator>
    </NavigationContainer>
  );
}
// Profile page
import { INavigationType, IRouteType } from '../types';

interface IProps {
  route: IRouteType<'Profile'>;
  navigation: INavigationType<'Profile'>;
}
function Profile ({
route,
navigation
}: IProps ) {
  const { userId } = route.params;
  
  useEffect(() => {
    props.navigate(PageName) // this not tip pageName or page arguments if the page need
  }, [])


  return (
    <Text>this is Profile page</Text>
  )
}

Using props.navigation(), it will provide tips on pageName and arguments correctly. Also, the PageComponent will not show errors if not specified as any.

Answer №1

My recommendation is to utilize the hook approach by incorporating useNavigation along with typescript annotation. With your existing definition of RootStackParamList, you can proceed as follows:

  import {useNavigation} from 'react-navigation/core'

  type RootStackProps =
  StackNavigationProp<RootStackParamList>;
  const navigation = useNavigation<RootStackProps>();

  navigation.navigate('Profile') <--- this guides the route and arguments

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

Different ways to utilize interface for nested functions

Can someone help me set a better topic for my question? I'm not sure how to do it :) Here's the scenario: I have two functions that share the same interface: interface createMailInterface { to: String, subject: String, message: String } ...

Encountering the error "tsx is not defined" during a Jest test in a React/TypeScript project

I'm currently working on implementing Jest tests within a React project that has enforced TypeScript settings. In a simple test.tsx file located in the test folder, I have the following code: import React from 'react'; describe('Test& ...

Angular 8: Implementing functionality for the Parent Component to detect when the User clicks outside of the Child Component Textbox

I am working on a scenario where I have a Parent Component and a Child Component containing a Formbuilder and a ZipCode textbox. Is there a way to notify the Parent Component when the user clicks out of the Child Component Textbox? I need to trigger some ...

The service being injected is not defined

Two services are involved in this scenario, with the first service being injected into the second service like so: rule.service.ts @Injectable() export class RuleService { constructor( private _resourceService: ResourceService ){} s ...

Tips for creating an interface in TypeScript that prevents access to uninitialized properties of a class

Interfaces still baffle me a bit. I understand that interfaces are typically used for public properties, but I want to create an interface that will prevent access to uninitialized properties. Currently, I am able to access this.material without any errors ...

The expression has been altered following verification. It previously read as 'model: 1777' but now states 'model: 2222'

I've been working on this HTML code that utilizes [(ngModel)] to update input values, and I want the Total, Subtotal, and Amount Paid fields to be automatically calculated when a change is made. However, I'm encountering some issues with this app ...

Blend the power of Node's CommonJS with the versatility of Typescript's ES modules

I currently have a Node.js v10 legacy application that was built using CommonJS modules (require). The entire codebase is written in JavaScript. However, I am considering upgrading the app and refactoring a specific part of it to use TypeScript modules ( ...

Tips for updating a boolean value in a JSON file with a button in Angular and TypeScript

Can someone guide me on how to create a function in my table-viewer.component.ts file that can update the status from "false" to "true" in a JSON file when a user clicks the cancel button? The JSON file has the following information. db.json "firstN ...

The predicate "adds" is applied to the type rather than substituting it

In my class, I am using a generic type to represent the known elements of its map, as shown below: abstract class Component { ... } class Test<Known extends Component[]> { components: Map<string, Component> ... has<C extends Compon ...

"Vue allows developers to define components by providing both template and script through the Vue()

I'm currently facing an issue while setting up a component within my global Vue() initialization. Surprisingly, I've managed to define the template for the component, but I'm struggling to specify the actual class that is executing the opera ...

Connecting a hybrid/web client application to established remote web services outlined through a set of WSDL specifications

Summarizing the Problem I am faced with the task of integrating a mobile hybrid application, likely built on Ionic, that will need to indirectly consume several SOAP web services. My goal is for the TypeScript client in the mobile app to have knowledge of ...

Upgrading a Basic ReactJS Example to Typescript

Beginner Inquiry I recently converted a ReactJS script from Javascript to Typescript. Is there a more concise way to do this without relying heavily on "any" types? Original Javascript version: const App = ({title}) => ( <div>{title}</div& ...

Passing a method from a component to a service in Angular 9

Recently, I've been working on some websocket code that involves sending a message to the server and receiving a reply. The current implementation is functional, but I'm looking to refactor it by encapsulating it within a service and then callin ...

Angular project facing issues during Maven build process

Hi there, I'm currently facing some challenges while trying to deploy my Angular and Spring Boot application. Whenever I run the command mvn clean compile spring-boot:run, I encounter a build failure from my Angular pom file. The error message I am r ...

Exploring the functionality of the scan operator within switchMap/mergeMap in RxJS

We're utilizing the scan operator to handle our 'load more' button within our table. This operator allows us to accumulate new results with the previous ones, but we've come across some unexpected behavior. Let's break it down by l ...

Ways to eliminate unnecessary re-rendering of components that remain unchanged?

I am struggling with a component that contains various other components, such as text fields. Whenever an input is made in the text field, all the components are re-rendered. My goal is to prevent this re-rendering and only update the component that has a ...

When TypeScript's Exclude<UnionOfTypes, Interface> is used, the resulting type is always "never"

What causes Exclude<A,B> to resolve to the never type in the code snippet below? Shouldn't the typescript compiler be able to infer (through static analysis) that A and B are extending Parent, leading to Exclude<Choices, Parent> resolving ...

Building an Event Scheduler in Outlook Calendar with Angular 5

Currently, I am utilizing Angular version 5.2 for a room booking portal project. One of the requirements entails adding an event to the Outlook calendar on the day a room is booked. The system includes a table listing all bookings, with a button in each ro ...

What could potentially occur if the sourcemap is configured to false within an Angular application?

Recently, I began learning Angular. While exploring my project files, I came across the sourcemap option in the tsconfig.json file, which is set to "sourceMap": true by default. I stumbled upon a helpful link on Stack Overflow that clarified some of my dou ...

show additional worth on the console

Just starting out with JavaScript. Trying to display additional values in the console. Uncertain about how to access add-ons. Can anyone help me troubleshoot? Here is my code snippet below: https://jsfiddle.net/6f8upe80/ private sports: any = { ...