I am currently working with a module
import pino, { Logger } from 'pino';
let logger: Logger;
if (process.env.NODE_ENV === 'production') {
const dest = pino.extreme();
logger = pino(dest);
}
if (process.env.NODE_ENV === 'development') {
// @ts-ignore
logger = pino({ prettyPrint: { colorize: true } });
}
...
export default logger;
// ^^^ [ts] Variable 'logger' is used before being assigned. [2454]
Under no circumstances is the logger undefined, but even if it were to be undefined, I am okay with that
How do I address the TypeScript error at the end:
Variable 'logger' is used before being assigned. [2454]
I have modified my code, yet the error persists
import pino, { Logger } from 'pino';
let logger: Logger;
if (process.env.NODE_ENV === 'production') {
const dest = pino.extreme();
logger = pino(dest);
} else
if (process.env.NODE_ENV === 'development') {
// @ts-ignore
logger = pino({ prettyPrint: { colorize: true } });
} else
if (process.env.NODE_ENV === undefined) {
throw new Error('Logger must be initialized! Set up process.env.NODE_ENV');
}
if (logger) { // <-- Variable 'logger' is used before being assigned. [2454]
// configuring process
}
export default logger;
Another approach could be
import pino, { Logger } from 'pino';
let logger: Logger;
function configureProcess(theLogger: Logger) {
// setup process with theLogger
}
if (process.env.NODE_ENV === 'production') {
const dest = pino.extreme();
logger = pino(dest);
configureProcess(logger); // <-- code duplication
} else if (process.env.NODE_ENV === 'development') {
// @ts-ignore
logger = pino({ prettyPrint: { colorize: true } });
configureProcess(logger); // <-- code duplication
}
if (process.env.NODE_ENV === undefined) {
throw new Error('Logger must be initialized! Set up process.env.NODE_ENV');
}
export default logger;
// ^^^ [ts] Variable 'logger' is used before being assigned. [2454]
I find myself in a constant battle against TypeScript instead of focusing on development - so many workarounds for an issue that isn't actually a problem