adonisjs / env

Framework agnostic environment variables parser and validator
https://docs.adonisjs.com/guides/environment-variables
MIT License
35 stars 10 forks source link

Undefined is not removed from types when passing a default value #19

Closed targos closed 3 years ago

targos commented 3 years ago

Package version

v2.0.5

Node.js and npm version

Node.js 14, npm 6

Sample Code (to reproduce the issue)

// in env.ts
import Env from '@ioc:Adonis/Core/Env';

export default Env.rules({
  OPTIONAL_STRING: Env.schema.string.optional(),
});

// in contracts/env.ts
declare module '@ioc:Adonis/Core/Env' {
  type CustomTypes = typeof import('../env').default;
  interface EnvTypes extends CustomTypes {}
}

// in some other file
import Env from '@ioc:Adonis/Core/Env';

const value = Env.get('OPTIONAL_STRING', 'defaultValue');
type ValueType = typeof value; // string | undefined

ValueType should be string because of the default value. This is important to avoid errors when passing the value returned by Env.get() to a function that requires a string. Additionally, I think the typings should only allow to pass a default value if the key was declared as optional.

thetutlage commented 3 years ago

Yup, it should not be undefined. Can you please create a PR to fix the behaviour?

Additionally, I think the typings should only allow to pass a default value if the key was declared as optional.

Agree, but this may require users to change a lot of their existing config after updating the package.

thetutlage commented 3 years ago

Closed by https://github.com/adonisjs/env/pull/22