Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Access value of env object by name #191

Open
sephentos opened this issue Aug 29, 2022 · 1 comment
Open

Access value of env object by name #191

sephentos opened this issue Aug 29, 2022 · 1 comment

Comments

@sephentos
Copy link

sephentos commented Aug 29, 2022

I'm trying to read a variable from the env object dynamically using a string variable as the property name, but I can't.

env.ts

import { bool, cleanEnv, port, str } from 'envalid'

export default cleanEnv( process.env, {
	NODE_ENV: str( { choices: ['development', 'production'] } ),
...
} )

typeof env: object

url.ts

import env from '@/env'

export function url( envName: string): string
{
	console.log(env[envName])
// Also does not work with env.[envName]
...

typeof envName: string

results in:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ NODE_ENV: "development" | "production"; ...

No index signature with a parameter of type 'string' was found on type '{ NODE_ENV: "development" | "production ...";

I don't really understand those error messages. Maybe someone could help me?
If not, is there another way to pass an env name to a function and use that to read the env value?
(e.g. call myFunc('URL_PRODUCTION') -> myFunc reads env.URL_PRODUCTION as env.[PARAM_NAME] / env[PARAM_NAME])

btw: reading process.env[envName] (bypassing envalid) works without issues

@af
Copy link
Owner

af commented Sep 3, 2022

Instead of typing envName as string could you try envName: keyof typeof env? I think that should do the trick, typescript is rightfully complaining because not just any string will be a valid key of the cleaned env object. Hope that helps!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants