You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何全局重写@react-native-firebase/messaging的RemoteMessage类型?

全局重写@react-native-firebase/messaging的RemoteMessage data类型

要实现无需显式指定参数类型就能获得自定义data的TypeScript智能提示,你需要通过模块扩展的方式覆盖原类型,而非全局命名空间。具体步骤如下:

1. 定义自定义数据类型

先明确你的自定义类型结构:

// 替换为你实际的PageType枚举或联合类型
type PageType = 'Home' | 'Detail' | 'Settings';

// 自定义的data结构
interface CustomRemoteMessageData {
  page: PageType;
  pageProps: {
    id: string;
    // 补充其他需要的属性
  };
}

2. 创建类型扩展文件

在项目根目录或src目录下创建messaging.d.ts(或沿用你的global.d.ts),内容如下:

import '@react-native-firebase/messaging';

declare module '@react-native-firebase/messaging' {
  interface RemoteMessage {
    // 直接覆盖原data属性的类型
    data: CustomRemoteMessageData;
  }
}

3. 确保TypeScript识别该文件

检查tsconfig.json,确保include数组包含这个d.ts文件:

{
  "include": [
    "src/**/*",
    "global.d.ts" // 或你的messaging.d.ts路径
  ]
}

为什么之前的方法无效?

你之前尝试的FirebaseMessagingTypes命名空间并非@react-native-firebase/messaging库暴露的类型结构,该库的RemoteMessage接口直接在模块@react-native-firebase/messaging下导出,因此必须通过模块扩展的方式覆盖类型。

完成配置后,调用messaging().onNotificationOpenedApp时,remoteMessage.data会自动使用你的自定义类型,无需显式指定参数类型就能获得完整智能提示。

内容的提问来源于stack exchange,提问作者luicfrr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 11:33:17