I have a log class that needs to define various convenience functions such as error
, warn
, info
, etc that all do the same thing: make a call to a log
function with their severity and the data to be logged.
This is verbose and wastes KBs:
class Logger {
error(...args: any[]): void {
this.log('error', ...args)
}
warn(...args: any[]): void {
this.log('warn', ...args)
}
// ...and so on
}
I currently have an enum of all the severities, and a union of strings of all the severities:
enum severityLevels {
error,
warn,
info
}
type severities = keyof typeof severityLevels
What I'd like to do is programmatically create functions for each severity level in the logger class's constructor (a very simple Object.keys(severityLevels).forEach(...)
in vanilla JS), however I can't figure out how to get TypeScript to allow this to happen. If I make an interface with all the severity function definitions, I can't implements
it (the functions don't already exist). If I make them optional, then calling those log functions (which "might not exist") gets messy.
Any ideas?