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

如何根据对象属性名定义多类型?Chrome扩展消息类型适配问题

解决Chrome扩展消息通信的TypeScript类型匹配问题

你需要的是联合类型,让每个action值对应唯一的value类型,而不是用Record(它生成的是键值对对象,不符合消息结构)。

正确的类型定义方式

保留你的Actions接口,通过映射类型+联合类型生成BackgroundMessage:

interface Actions {
  setUpdate: { total: number; alarm: boolean };
  setReminder: { text: string; when: Date };
}

// 生成每个action对应的消息类型,再组合成联合类型
type BackgroundMessage = {
  [K in keyof Actions]: {
    action: K;
    value: Actions[K];
  };
}[keyof Actions];

效果说明

这个类型会自动展开为以下联合类型:

{ action: 'setUpdate'; value: { total: number; alarm: boolean } } | 
{ action: 'setReminder'; value: { text: string; when: Date } }

在你的onMessage监听函数里,TypeScript会自动做类型窄化:当switch匹配到case 'setUpdate'时,message.value会被推断为{ total: number; alarm: boolean },无需额外类型断言。

验证示例

前端发送的消息会被TypeScript校验:

// ✅ 合法:action和value类型匹配
chrome.runtime.sendMessage({ action: 'setUpdate', value: { total: 4, alarm: false } });

// ❌ 非法:value类型不匹配action
chrome.runtime.sendMessage({ action: 'setUpdate', value: { text: 'test' } });

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 00:25:17