FCM从Legacy API迁移至HTTP V1 API时TypeScript类型错误问题
我正在将FCM从Legacy API迁移到HTTP V1 API,迁移前后代码如下:
迁移前(Legacy API)代码
const payload = { data: { title: "Alert: New Query", body: "You have received a new order query", icon: "default" } } const options = { priority: "high" } await admin.messaging().sendToDevice(pharmToken, payload, options)
迁移后(HTTP V1 API)代码
const message = { name: 'Alert', notification: { title: 'Alert: New Query!' }, data: { title: "Alert: New Query", body: "You have received a new order query", icon: "default" }, android: { notification: { title: "Alert: New Query", body: "You have received a new order query", icon: "default" }, priority: "high", }, token: pharmToken, } await admin.messaging().send(message)
但TypeScript在await admin.messaging().send(message)的message参数处报错,错误信息:
Argument of type '{ name: string; notification: { title: string; }; data: { title: string; body: string; icon: string; }; android: { notification: { title: string; body: string; icon: string; sound: string; }; priority: string; }; token: any; }' is not assignable to parameter of type 'Message'.
Type '{ name: string; notification: { title: string; }; data: { title: string; body: string; icon: string; }; android: { notification: { title: string; body: string; icon: string; sound: string; }; priority: string; }; token: any; }' is not assignable to type 'TokenMessage'.
The types of 'android.priority' are incompatible between these types.
Type 'string' is not assignable to type '"high" | "normal" | undefined'
使用的是Firebase Admin SDK。
问题原因
Firebase Admin SDK的TypeScript类型定义中,android.priority的类型是字面量类型"high" | "normal" | undefined,而代码中"high"被TypeScript推断为普通string类型,导致类型不兼容。
解决方法
有两种方式可以修复这个类型错误:
- 使用
as const强制字面量类型推断
将priority: "high"改为priority: "high" as const,让TypeScript识别这是固定的字面量值而非通用字符串:
const message = { // ...其他字段 android: { notification: { title: "Alert: New Query", body: "You have received a new order query", icon: "default" }, priority: "high" as const, }, token: pharmToken, }
- 用SDK内置类型约束变量
直接导入并使用TokenMessage类型定义变量,TypeScript会自动校验所有字段的类型:
import { TokenMessage } from "firebase-admin/messaging"; const message: TokenMessage = { name: 'Alert', notification: { title: 'Alert: New Query!' }, data: { title: "Alert: New Query", body: "You have received a new order query", icon: "default" }, android: { notification: { title: "Alert: New Query", body: "You have received a new order query", icon: "default" }, priority: "high", }, token: pharmToken, }
另外注意:错误信息中提到android.notification存在sound: string字段,但迁移后代码里未定义,若为笔误请保持代码与实际逻辑一致。
内容的提问来源于stack exchange,提问作者oTwo

