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

如何基于ErrorCodes自动推断formatMessage的剩余参数类型?

基于ErrorCodes自动推断formatMessage参数类型的实现问题

相关代码文件

./errorCodes.ts

export enum ErrorCodes {
  ErrorCode1,
  ErrorCode2,
  ErrorCode3
}

./errorMessages.ts

export const ErrorMessages = {
  [ErrorCodes.ErrorCode1]: (a1: string, a2: string) => `${a1} ${a2} message1...`,
  [ErrorCodes.ErrorCode2]: (a1: boolean) => `${a1} message2...`,
  [ErrorCodes.ErrorCode3]: `message3...`
}

./formatMessage.ts

import {ErrorCodes} from "./errorCodes"
import {ErrorMessages} from './errorMessages'

export const formatMessage = (
  code: ErrorCodes,
  ...args: Parameters<typeof ErrorMessages[typeof ErrorCodes[typeof code]]>
  // ^ Type '{ 0: (a1: string, a2: string) => string; 1: (a1: boolean) => string; 2: string; }' has no matching index signature for type 'string'.ts(2537)
) => {
  const message = ErrorMessages[code];
  const errorCode = `[${ErrorCodes[code]}]`;

  switch (typeof message) {
    case "string": {
      return [errorCode, message].join(" ");
    }
    case "function": {
      return [errorCode, message(...args)].join(" ");
      /**                              ^
       A spread argument must either have a tuple type or be passed to a rest parameter. ts(2556)
       */
    }
  }
}

尝试的方案及问题

我尝试用以下类型定义来实现参数推断:

...args: Parameters<typeof ErrorMessages[typeof ErrorCodes[typeof code]]>

但实际使用中存在两个问题:

  • 调用formatMessage时没有参数智能提示
  • 一旦ErrorMessages中加入字符串类型的消息值,整个类型推断逻辑就会失效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 08:25:16