Hello, I am migrating to v1 and moving from `js` s...
# help
b
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
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
Thanks @manitej, I have a lot of variables so I am trying to find more clear way
r
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
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
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
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
yeah that's nice, thanks @Dan Coates
r
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;
}