https://serverless-stack.com/ logo
#help
Title
# help
b

Bshr Ramadan

05/20/2022, 5:39 AM
Hello, I am migrating to v1 and moving from
js
stacks to
ts
when set a function env variable to a process env var, I am getting this type safety error:
Copy code
Type 'string | undefined' is not assignable to type 'string'.
I can put it like so:
Copy code
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?
m

manitej

05/20/2022, 5:42 AM
you can try something like this,
Copy code
// 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");
b

Bshr Ramadan

05/20/2022, 5:44 AM
Thanks @manitej, I have a lot of variables so I am trying to find more clear way
r

Ross Coundon

05/20/2022, 5:45 AM
Alternatively you could define a
process.d.ts
file with the values that you expect. e.g.
Copy code
declare namespace NodeJS {
  export interface ProcessEnv {
    GOOGLE_CLIENT_ID: string; // assert always present
    SOMETHING_ELSE?: string; // optional - need to check in code
  }
}
t

thdxr

05/20/2022, 5:46 AM
You can assert by doing
process.env.THING!
oh you want it to throw an error
I would just run type checking before deployment
Another more advanced technique involves using js proxies
or just your own function that you pass in the string of the variable and it throws if it's not there
b

Bshr Ramadan

05/20/2022, 6:01 AM
Thank you @Ross Coundon @thdxr for your nice solutions. I think if I used assertion with
!
, sst will throw an error in building time if the variable is
undefined
and I think that's enough for me now 😁
d

Dan Coates

05/20/2022, 6:56 AM
Another simple solution that I use quite often is to have a function like:
Copy code
function 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:
Copy code
environment: {
  var: ensureEnvVar('MY_ENV_VAR')
}
b

Bshr Ramadan

05/20/2022, 6:59 AM
yeah that's nice, thanks @Dan Coates
r

Ross Coundon

05/20/2022, 7:23 AM
Another way…is to define a type predicate function that you can use to check the env var like this:
Copy code
function isEnvVarSpecified(envVar: string): envVar is string {
  if (!envVar || typeof envVar !== 'string') {
    return false;
  }
  return true;
}