从@react-native-async-storage/async-storage导入AsyncStorage遇类型错误
问题说明
安装完@react-native-async-storage/async-storage后,导入AsyncStorage时出现类型错误,提示:
类型“AsyncStorageStatic”缺少类型“IAsyncStorage<string, any>”中的以下属性:store、size、getStorets(2739
问题原因
这是类型定义不兼容导致的:官方AsyncStorage的AsyncStorageStatic类型,和你代码中依赖的IAsyncStorage<string, any>接口要求的属性不匹配。要么是你自己定义了IAsyncStorage接口,要么是某个依赖库封装了自定义存储接口,而官方AsyncStorage本身并不提供store、size、getStore这些方法。
解决办法
调整自定义接口对齐官方API
如果IAsyncStorage是你自己定义的接口,直接修改它的方法和属性,和官方AsyncStorage的API保持一致。官方核心方法为getItem、setItem、removeItem、clear等,把store改成setItem,getStore改成getItem,移除size这类官方没有的属性。封装官方AsyncStorage适配接口
若无法修改IAsyncStorage接口,写个封装层转换方法:import AsyncStorage from '@react-native-async-storage/async-storage'; const CustomStorage: IAsyncStorage<string, any> = { async store(key: string, value: any) { await AsyncStorage.setItem(key, JSON.stringify(value)); }, async size() { const keys = await AsyncStorage.getAllKeys(); return keys.length; }, async getStore(key: string) { const value = await AsyncStorage.getItem(key); return value ? JSON.parse(value) : null; }, // 补充IAsyncStorage要求的其他方法 }; export default CustomStorage;之后代码里导入这个
CustomStorage即可。排查第三方库的类型冲突
如果是第三方库依赖IAsyncStorage类型,查看该库的文档,确认是否有适配官方AsyncStorage的方案或工具类。
内容的提问来源于stack exchange,提问作者ceejam

