React Native集成RevenueCat时常量传参遇字符串类型错误求助
解决React Native中RevenueCat API密钥类型不匹配问题
你遇到的const apikey : google string类型错误,本质是TypeScript类型推断与RevenueCat的configure方法参数类型约束不兼容导致的。RevenueCat的TypeScript定义对不同平台的API密钥参数有类型限制,而当前APIKeys对象的类型被推断为包含apple和google字符串属性的通用对象,TypeScript无法确认你传入的是对应平台的合法密钥类型。
修改方案一:明确APIKeys的类型
通过类型声明约束APIKeys的属性类型,让TypeScript能正确识别平台对应的密钥:
// 定义平台密钥类型 type PlatformAPIKeys = { apple: string; google: string; }; const APIKeys: PlatformAPIKeys = { apple: "appl_KDUGooX", google: "your_revenuecat_api_key", };
修改方案二:调用configure时添加类型断言
在传入密钥时直接断言类型,快速绕过TypeScript的类型检查:
useEffect(() => { const fetchData = async () => { Purchases.setDebugLogsEnabled(true); if (Platform.OS === "android") { await Purchases.configure({ apikey: APIKeys.google as const }); } else { await Purchases.configure({ apikey: APIKeys.apple as const }); } const offering = await Purchases.getOfferings(); const customerInfo = await Purchases.getCustomerInfo(); // 更新组件状态 setCurrentOffering(offering.current); setCustomerInfo(customerInfo); }; fetchData(); // 原代码未执行初始化函数,需添加此调用 }, []);
额外注意
原代码中useEffect内部仅定义了fetchData函数但没有执行,这会导致RevenueCat完全没有初始化,一定要加上fetchData()调用。
内容的提问来源于stack exchange,提问作者June Nouh
相关产品推荐
相关产品推荐

