React Navigation + TypeScript Error: Type 'EventStackParams' không thỏa mãn ràng buộc 'Record <string, object | không xác định> '

Nov 18 2020

Tôi đang thêm TypeScript vào Bộ điều hướng React Native / React Navigation 5 của mình, nhưng gặp sự cố với việc Thêm EventStackParamsvào createStackNavigator().

Tôi đã xem qua React Native 5 Docs , StackOverflow và GitHub, nhưng không may mắn. Tôi đang làm gì sai? Dưới đây là lỗi của tôi và mã

Lỗi:

Type 'EventStackParams' does not satisfy the constraint 'Record<string, object | undefined>'.

Index signature is missing in type 'EventStackParams'.ts(2344)

Navigation.tsx:

// Imports: TypeScript Types
import { EventStackParams } from '../types/types';

// React Navigation: Stack Navigators
const RootStack = createStackNavigator();
const EventsStack = createStackNavigator<EventStackParams>();

// Events Navigator
const EventsNavigator = () => (
  <EventsStack.Navigator initialRouteName="Events">
    <EventsStack.Screen
      name="Events"
      component={Events}
      options={{
        title: '',
        headerShown: false,
      }}
    />

    <EventsStack.Screen
      name="EventDetails"
      component={EventDetails}
      options={{
        title: '',
        headerShown: true,
        headerStyle: {
          elevation: 0,
          shadowOpacity: 0,
          borderBottomWidth: 0,
        },
      }}
    />
  </EventsStack.Navigator>
);

EventDetails.tsx

// Imports: Dependencies
import { RouteProp } from '@react-navigation/native';

// Imports: TypeScript Types
import { ReduxState, EventStackParams } from '../../types/types';

// React Hooks: React Navigation
const route = useRoute<RouteProp<EventStackParams, 'EventDetails'>>();

Các loại.tsx:

// TypeScript Type: Event
export interface Event {
  eventTitle: string,
  eventDescription: string | null,
  eventStreet: string,
  eventLocation: string,
  eventLatitude: number,
  eventLongitude: number,
  eventDateStart: number,
  eventDateEnd: number,
  eventTimeStart: string,
  eventTimeEnd: string,
};

// TypeScript Type: Event Stack Params
export interface EventStackParams {
  Events: undefined,
  EventDetails: {
    item: Event,
  },
};

Trả lời

1 jefelewis Nov 19 2020 at 00:31

Cập nhật:

Điều này đã được khắc phục bằng cách thay đổi interfacethành type.

// TypeScript Type: Event Stack Params
export type EventStackParams = {
  Events: undefined,
  EventDetails: {
    item: Event,
  },
};