keithmorris / node-dotenv-extended

A module for loading .env files and optionally loading defaults and a schema for validating all values are present.
MIT License
111 stars 24 forks source link

[Feature proposal] Use .d.ts as schema for type safety #38

Open lhhong opened 4 years ago

lhhong commented 4 years ago

This proposal adds type safety for typescript by providing the ability to use type declarations directly as a schema. With schema checking, we can take advantage of the fact that this library ensures the respective keys in process.env will be present.

Existing solutions are not as great. We could litter the typescript code with if KEY !== undefined or with !! operator but risk having typographical errors. Having process.env type declaration facilitates code completion. While we can use a type declaration separate from the schema, being able to have one single source of truth avoids the need to change multiple places.

Notes

  1. README not updated
  2. Union string types not supported, future additions could include that with checking
  3. I have also considered declaration code generation but it can be painful for a small project without proper build pipelines

Breaks: type declaration of IEnvironmentMap changed to { [name: string]: string | undefined }. I believe dotenv's type declaration of { [name: string]: string } is a mistake. With this change, it no longer makes sense to carry this mistake down.