如何基于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
相关产品推荐
相关产品推荐

