You need to enable JavaScript to run this app. 如何为泛型WebSocket handler编写TypeScript类型以避免强制类型转换
优惠活动
大模型
产品
解决方案
定价
更多

如何为泛型WebSocket handler编写TypeScript类型以避免强制类型转换

泛型WebSocket类型标注实现方案

核心实现思路为预先统一定义全局消息类型映射,基于映射关系做全链路类型推导,完全避免业务层手动类型断言。


1. 定义全局消息类型映射

将所有WebSocket消息的类型字符串与对应的数据结构做绑定,后续所有类型推导均基于该映射生成:

// 统一定义所有WebSocket消息的<类型字符串: 数据结构>映射
interface WSMessageMap {
  "use-search-results": PlannerTypes.SearchResults;
  // 新增消息只需在此处添加条目即可,示例:
  "user-status-change": { userId: string; status: "online" | "offline" };
  "notification-push": { id: string; content: string; timestamp: number };
}

2. 改造基础类型与PersistentWebsocket类

// 基于映射生成通用消息类型
type WSMessage<T extends keyof WSMessageMap = keyof WSMessageMap> = {
  type: T;
} & WSMessageMap[T];

// 泛型Handler函数类型
type HandlerFunc<T extends keyof WSMessageMap = keyof WSMessageMap> = (data: WSMessage<T>) => void;

class PersistentWebsocket {
  // 给订阅集合增加类型标注
  private subscriptions: {
    [K in keyof WSMessageMap]?: Array<HandlerFunc<K>>
  } = {};

  // 补充socket类型声明,可根据实际环境替换为对应WebSocket实现类型
  private socket!: WebSocket;

  initializeWebsocket(): void {
    this.socket.onmessage = (event) => {
      const message = JSON.parse(event.data) as WSMessage;
      this.processMessage(message);
    };
  }

  processMessage(message: WSMessage): void {
    const handlers = this.subscriptions[message.type];
    if (!handlers) return;
    for(const handler of handlers) {
      // 此处为框架层安全类型断言,业务层无感知
      handler(message as WSMessage<typeof message.type>);
    }
  }

  // 补充subscribe方法泛型标注
  subscribe<T extends keyof WSMessageMap>(type: T, handler: HandlerFunc<T>): void {
    if (!this.subscriptions[type]) {
      this.subscriptions[type] = [];
    }
    this.subscriptions[type]!.push(handler);
  }

  // 补充unsubscribe方法泛型标注
  unsubscribe<T extends keyof WSMessageMap>(type: T, handler: HandlerFunc<T>): void {
    const handlers = this.subscriptions[type];
    if (!handlers) return;
    this.subscriptions[type] = handlers.filter(h => h !== handler) as typeof handlers;
  }
}

3. 改造useWebsocketSubscription hook

export function useWebsocketSubscription<T extends keyof WSMessageMap>(
    websocket: PersistentWebsocket,
    type: T,
    handler: HandlerFunc<T>,
): void {
    useEffect(() => {
        websocket.subscribe(type, handler);
        return () => {
            websocket.unsubscribe(type, handler);
        };
    // 补充依赖项避免重复执行
    }, [websocket, type, handler]);
}

4. 业务调用示例(无冗余类型断言)

useWebsocketSubscription(websocket, "use-search-results", (data) => {           
    // data自动推导为 PlannerTypes.SearchResults & { type: "use-search-results" } 类型
    setActivityOptions(data.results.activities);                                   
    setLocationOptions(data.results.locations);                                    
    setMode(DisplayMode.search);                                                
});

扩展说明

  • 如果需要PersistentWebsocket支持多场景复用,可将WSMessageMap作为泛型参数提到类定义上,无需全局固定映射
  • 所有类型校验均为静态编译阶段生效,不会影响运行时性能

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 04:15:00