Say I got this .env.local file:
SOME_VAR="this is very secret"
SOME_OTHER_VAR="this is not so secret, but needs to be different during tests"
is there any way I can programmatically get typescript to make a type like this:
type TEnv = 'SOME_VAR' | 'SOME_OTHER_VAR'
The use case I have goes like this
export default function env(key: TEnv): string {
return process.env[key] || Cypress.env(key)
}
I'm thinking that I could perhaps trigger a script that read the keys via dotenv (or bash) and then writes a types.d.ts file with them... But just wanted to hear if there is already a TS way to do this?
My latest attempt looks like this
import dotenv from 'dotenv'
class DynamicArray<T> {
add(value: T): Array<T> {
let collection = new Array<T>()
collection.push(value)
return collection
}
}
const TEnvKey = new DynamicArray<string>()
const envFile = dotenv.config({ path: '.env.local' }).parsed
Object.keys(envFile).forEach((key) => TEnvKey.add(key))
export default function env(variable: TEnvKey): string {
return process.env[variable] || Cypress.env(variable)
}
But that does not work..
Side note
The webpack used by NextJS does not allow process.env[key] and Cypress will throw a reference error. So had to do it like this:
export default function env(key: TEnvKey): string {
try {
// have to try catch because of Cypress reference error
return Cypress.env(key)
} catch {
switch (key) {
case 'SOME_VAR':
return process.env.SOME_VAR
case 'SOME_OTHER_VAR':
return process.env.SOME_OTHER_VAR
default:
return undefined
}
}
}