This content originally appeared on DEV Community and was authored by Júnior Mendes
If you're working with NodeJS applications, you probably has process.env.VARIABLE
statements all around your code base. The most simple method to configure an application is installing dotenv and creating that lovely .env file on the root folder of your project.
This approach, however, has some pitfalls and is error prone. What if you don't set that process.env port? You'll probably have a default value (maybe 3000?), but you will need to run your application to discover such type of thing.
That same problem is solve by typescript for almost anything. When you have the help of static typing, you can discover errors a lot faster. That said, how can you use Typescript to have a type-safe way to access configurations?
Show me the code!
Take a look at that short snippet:
export class EnvironmentService<Environment> {
public constructor(
private readonly variables: Environment
) {
// some logic to assign process.env to this.variables
// you can use, for instance,
this.variables = Joi.attempt<Environment>(process.env))
}
public get<T>(name: keyof Environment) {
return <T><unknown>this.variables[name];
}
}
In a nutshell,
- You define an interface for you environment;
- Then you pass it as a type argument to the EnvironmentService class when instantiating a new object;
- Finally, you use something like class-validator, Joi or you library of choice to assert if the
process.env
object has all required variables and assign its value to thevariables
attribute;
After those simple steps, you can use the method get
to get all possible environment variables with the help of typescript to guide your choice - and if you need, you can cast the value to some desired type:
Conclusion
That's all folks! If you liked that simple content, don't forget to comment and share with someone you might help. Also, that's my first attempt to write something in english: if you see something wrong, just message me on Twitter (@dotmendes ).
References
This content originally appeared on DEV Community and was authored by Júnior Mendes

Júnior Mendes | Sciencx (2021-06-07T20:11:41+00:00) Making a dead simple configuration service with Typescript. Retrieved from https://www.scien.cx/2021/06/07/making-a-dead-simple-configuration-service-with-typescript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.