My TypeScript project includes a file that loads environment variables and exports them:
const.ts:
const {
VARIABLE0, // type of VARIABLE0 is string | undefined
VARIABLE1,
} = process.env;
if (!VARIABLE0 || !VARIABLE1) {
throw new Error('Invalid env');
}
console.log(VARIABLE0); // type of VARIABLE0 is string
console.log(VARIABLE0.length);
export {
VARIABLE0, // type VARIABLE0 is string | undefined
VARIABLE1,
};
I am puzzled as to why the exported type is string | undefined
even though I have checked for its existence. When I hover over VARIABLE0
after the check in VS Code, it shows as string
, but during export, it is string | undefined
. This inconsistency causes inconvenience in other parts of my code where I need to use these variables because I have to add ?
and !
in numerous places (e.g.,
const length = VARIABLE0?.length!
instead of const length = VARIABLE0.length
).
Is there a way to export it as string
without the undefined
part?
One approach I can think of is:
const {
VARIABLE0: VARIABLE0_TEMP, VARIABLE1: VARIABLE1_TEMP,
} = process.env;
if (!VARIABLE0_TEMP || !VARIABLE1_TEMP) {
throw new Error('Invalid env');
}
const VARIABLE0 = <string>VARIABLE0_TEMP;
const VARIABLE1 = <string>VARIABLE1_TEMP;
export {
VARIABLE0, VARIABLE1,
};
However, this solution may not be optimal as it is quite verbose, especially since I have around 10 variables to export in a similar manner.