Firebase Functions中Message类型的TypeScript适配问题求解
问题1:对象字面量匹配Message类型时报错
尝试用对象字面量模拟Message类型:
import type { Message } from 'firebase-functions/v1/pubsub' const data = 'base64 string' const message = { data, attributes: {}, /** @hidden */ _json: vi.fn(), json: vi.fn(), toJSON: vi.fn(), } satisfies Message
得到错误提示:
Type '{ data: string; attributes: {}; _json: Mock<any, any>; json: Mock<any, any>; toJSON: Mock<[], any>; }' does not satisfy the expected type 'Message'.
Property '_json' is private in type 'Message' but not in type '{ data: string; attributes: {}; _json: Mock<any, any>; json: Mock<any, any>; toJSON: Mock<[], any>; }'.
问题2:实例化Message类后data为undefined
直接实例化Message类:
import { Message } from 'firebase-functions/v1/pubsub' const message = new Message(data) console.log(message)
输出结果:
Message { data: undefined, attributes: {}, _json: undefined }
解决方案
1. 绕过私有属性的类型检查
Message的_json是私有属性,TypeScript不允许在对象字面量中显式声明私有属性来匹配类型,可通过以下两种方式解决:
方式一:类型断言跳过检查
如果是测试场景(比如用vitest模拟方法),直接用类型断言绕过私有属性的校验:
import type { Message } from 'firebase-functions/v1/pubsub' import { vi } from 'vitest' const data = 'base64 string' const message = { data, attributes: {}, json: vi.fn(), toJSON: vi.fn(), } as Message
方式二:提取公共属性创建模拟类型
如果不想用断言,可以提取Message的公共属性定义自定义类型,再模拟对象:
import type { Message } from 'firebase-functions/v1/pubsub' import { vi } from 'vitest' // 只提取需要用到的公共属性 type MockMessage = Pick<Message, 'data' | 'attributes' | 'json' | 'toJSON'> const data = 'base64 string' const message: MockMessage = { data, attributes: {}, json: vi.fn(), toJSON: vi.fn(), }
2. 正确实例化Message类
Message的构造函数要求传入包含data和attributes的配置对象,而非直接传入base64字符串,正确写法如下:
import { Message } from 'firebase-functions/v1/pubsub' const data = 'base64 string' // 传入包含data和attributes的对象 const message = new Message({ data, attributes: {} }) console.log(message) // 输出:Message { data: 'base64 string', attributes: {}, _json: undefined }
测试场景额外提示
单元测试中模拟Message对象时,无需完全匹配整个类型——私有属性_json通常不会在业务代码中直接调用,只需要模拟业务用到的属性和方法即可。
内容的提问来源于stack exchange,提问作者Rodrigo

