I am trying to find a way to automatically create an object with values computed during compilation using enumeration values and pre-defined function calls. The basic concept is to associate certain arguments of a function with keys. For example, consider the following:
enum LogLevel {
error = 'error',
warning = 'warning'
info = 'info'
}
const log = (level: LogLevel, message: string) => {
console.log(`Level: ${level}, Message: ${message}`);
}
I want to achieve something like this in terms of syntax:
const logger = {
[level in LogLevel]: (msg: string) => log(level, msg)
}
This code snippet does not work as expected and results in a compilation failure (
A computed property name must be of type 'string', 'number', 'symbol', or 'any'
).
I would like this to be equivalent to:
const logger = {
[LogLevel.error]: (msg: string) => log(LogLevel.error, msg),
[LogLevel.warning]: (msg: string) => log(LogLevel.warning, msg),
[LogLevel.info]: (msg: string) => log(LogLevel.info, msg)
}
This enables me to use it in this manner:
logger.error("Bad things happened")
logger.warn("Help me")
In my actual scenario, there are numerous elements in the enumeration, and I prefer not to manually update the object each time a new one is added. I understand that I can enforce a type constraint requiring all keys from the enumeration to be present in the type, using a similar syntax:
type Logger = {
[level in LogLevel]: (msg: string) => void
}
However, since the values are redundant and essentially boilerplate, I aim to have them generated automatically.