Bshr Ramadan
05/20/2022, 5:39 AMjs
stacks to ts
when set a function env variable to a process env var, I am getting this type safety error:
Type 'string | undefined' is not assignable to type 'string'.
I can put it like so:
environment: {
var: process.env.var || ''
}
but In case I forgot to set an env var, I want it to be undefined
and throw error in building time to notice it.
So how can I get rid of this type of error?manitej
05/20/2022, 5:42 AM// Throw error if client ID & secret are not provided
if (!process.env.GOOGLE_CLIENT_ID || !process.env.GOOGLE_CLIENT_SECRET)
throw new Error("Please set GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET");
Bshr Ramadan
05/20/2022, 5:44 AMRoss Coundon
05/20/2022, 5:45 AMprocess.d.ts
file with the values that you expect.
e.g.
declare namespace NodeJS {
export interface ProcessEnv {
GOOGLE_CLIENT_ID: string; // assert always present
SOMETHING_ELSE?: string; // optional - need to check in code
}
}
thdxr
05/20/2022, 5:46 AMprocess.env.THING!
thdxr
05/20/2022, 5:47 AMthdxr
05/20/2022, 5:47 AMthdxr
05/20/2022, 5:48 AMthdxr
05/20/2022, 5:48 AMBshr Ramadan
05/20/2022, 6:01 AM!
, sst will throw an error in building time if the variable is undefined
and I think that's enough for me now 😁Dan Coates
05/20/2022, 6:56 AMfunction ensureEnvVar(name: string) {
const value = process.env[name];
if(!value) throw new Error(`env var ${name} is missing`);
return value;
}
then when you want to use an env var you do:
environment: {
var: ensureEnvVar('MY_ENV_VAR')
}
Bshr Ramadan
05/20/2022, 6:59 AMRoss Coundon
05/20/2022, 7:23 AMfunction isEnvVarSpecified(envVar: string): envVar is string {
if (!envVar || typeof envVar !== 'string') {
return false;
}
return true;
}