React Navigation + TypeScript 错误:类型“EventStackParams”不满足约束“Record<string, object |未定义>'
Posted
技术标签:
【中文标题】React Navigation + TypeScript 错误:类型“EventStackParams”不满足约束“Record<string, object |未定义>\'【英文标题】:React Navigation + TypeScript Error: Type 'EventStackParams' does not satisfy the constraint 'Record<string, object | undefined>'React Navigation + TypeScript 错误:类型“EventStackParams”不满足约束“Record<string, object |未定义>' 【发布时间】:2021-03-02 07:50:52 【问题描述】:我正在将 TypeScript 添加到我的 React Native/React Navigation 5 Navigator,但在将 EventStackParams
添加到 createStackNavigator()
时遇到问题。
我浏览了React Native 5 Docs、*** 和 GitHub,但没有运气。我究竟做错了什么?以下是我的错误和代码
错误:
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'>>();
Types.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,
,
;
【问题讨论】:
【参考方案1】:更新:
已通过将 interface
更改为 type
来解决此问题。
// TypeScript Type: Event Stack Params
export type EventStackParams =
Events: undefined,
EventDetails:
item: Event,
,
;
【讨论】:
以上是关于React Navigation + TypeScript 错误:类型“EventStackParams”不满足约束“Record<string, object |未定义>'的主要内容,如果未能解决你的问题,请参考以下文章
我需要下载 react-navigation 并使用命令 npm i @react-navigation/native 并显示错误
React Navigation V2:navigation.push 和 navigation.navigate 的区别