Struggling to generate a solution that infers the arguments for an ErrorMessage
based on the provided code
input.
./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]]>
) => {
const message = ErrorMessages[code];
const errorCode = `[${ErrorCodes[code]}]`;
switch (typeof message) {
case "string": {
return [errorCode, message].join(" ");
}
case "function": {
return [errorCode, message(...args)].join(" ");
}
}
Attempting to define the arguments dynamically:
...args: Parameters<typeof ErrorMessages[typeof ErrorCodes[typeof code]]>
Encountering some challenges:
- Lack of autocomplete functionality when calling the function.
- Adding
string
returns inErrorMessages
caused type errors.