user14263509
user14263509

Reputation:

React Navigation w/ TypeScript: How to properly type out screen params? Property id does not exist on type object.ts(2339)

I'm not wrapping my head around how the types work for screen params. I looked at the documentation (https://reactnavigation.org/docs/typescript/) but I have no idea where they got the user.id from.

Here is what is going on with my application. I'm sending the id of the chat room when a user clicks on a chat.

types.tsx - This is where I added my ChatRoom: { id: string }

import { BottomTabScreenProps } from '@react-navigation/bottom-tabs';
import {
  CompositeScreenProps,
  NavigatorScreenParams,
} from '@react-navigation/native';
import { NativeStackScreenProps } from '@react-navigation/native-stack';

declare global {
  namespace ReactNavigation {
    interface RootParamList extends RootStackParamList {}
  }
}

export type RootStackParamList = {
  Home: NavigatorScreenParams<RootTabParamList> | undefined;
  Modal: undefined;
  NotFound: undefined;
  ChatRoom: { id: string };
};

export type RootStackScreenProps<Screen extends keyof RootStackParamList> =
  NativeStackScreenProps<RootStackParamList, Screen>;

export type RootTabParamList = {
  TabOne: undefined;
  TabTwo: undefined;
};

export type RootTabScreenProps<Screen extends keyof RootTabParamList> =
  CompositeScreenProps<
    BottomTabScreenProps<RootTabParamList, Screen>,
    NativeStackScreenProps<RootStackParamList>
  >;

ChatRoomItem.tsx - This is where I add the Pressable to navigate to 'ChatRoom' with the params of { id: roomId }

interface Props {
  roomId: string;
  uri: string;
  newMessages?: number;
  name: string;
  createdAt: string;
  lastMessage: string;
}

const ChatRoomItem: React.FC<Props> = ({
  roomId,
  uri,
  newMessages,
  name,
  createdAt,
  lastMessage,
}) => {
  const navigation = useNavigation();

  const openChat = () => {
    navigation.navigate('ChatRoom', {
      id: roomId,
    });
  };

ChatRoomScreen.tsx - This is where the I am getting the error

const ChatRoomScreen = () => {
  const route = useRoute();

  // Property 'id' does not exist on type 'object'.ts(2339)
  const roomId = route.params?.id; 

  // Logs correct roomId
  console.log(roomId); 

  return (

What is the proper way of fixing this error? Thanks for your help. First time using TypeScript with a React Native project so I want to understand these param types.

Upvotes: 0

Views: 2333

Answers (1)

You have to declare the type of your param in order to use them with useRoute

type ParamList = {
  Params: {id:string};
};

const { params } = useRoute<RouteProp<ParamList, 'Params'>>();

Upvotes: 2

Related Questions