如何指定react-native-calendars库@types定义的TItem泛型,解决参数隐式any问题
解决方案
- 首先定义你业务中日历项的自定义类型,按你实际的数据结构声明字段即可,示例如下:
// 可根据实际业务需求扩展字段 interface CalendarItem { name: string; id?: string; description?: string; }
- 有两种方式指定类型,推荐第二种全局绑定泛型的方案,所有关联回调都会自动获得正确类型:
- 方式一:单独给
renderItem的参数加类型
function renderItem(item: CalendarItem) { return ( <TouchableOpacity onPress={() => Alert.alert(item.name)}> <Text>{item.name}</Text> </TouchableOpacity> ); }
- 方式二:给
Agenda组件显式传入泛型参数,全局绑定类型(推荐)
该方案下loadItemsForMonth、rowHasChanged等所有和条目相关的回调参数都会自动匹配你定义的CalendarItem类型,不需要单独给每个回调加类型:
<Agenda<CalendarItem> items={state.items} loadItemsForMonth={loadItems.bind(this)} selected={'2017-05-16'} renderItem={renderItem.bind(this)} renderEmptyDate={renderEmptyDate.bind(this)} rowHasChanged={rowHasChanged.bind(this)} showClosingKnob={true} />
- 额外配置说明:如果你的state还没有定义类型,需要同步对齐声明:
// 以useState场景为例 const [state, setState] = useState<{ items: Record<string, CalendarItem[]> }>({ items: {} })
配置完成后TypeScript就可以正确识别item的所有属性,不会再报隐式any的错误。
内容的提问来源于stack exchange,提问作者m.umar
相关产品推荐
相关产品推荐

