motdotla / dotenv

Loads environment variables from .env for nodejs projects.
https://www.dotenvx.com
BSD 2-Clause "Simplified" License
19.04k stars 854 forks source link

DotenvPopulateInput not compatible with NodeJS.ProcessEnv #767

Closed mak3 closed 1 year ago

mak3 commented 1 year ago

Seems that populate method just never worked in Typescript. process.env may contain an undefined value in dict, making it unassignable.

import dotenv = require('dotenv')

const parsed = { HELLO: 'world' }
dotenv.populate(process.env, parsed)

Argument of type 'ProcessEnv' is not assignable to parameter of type 'DotenvPopulateInput'. 'string' index signatures are incompatible. Type 'string | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'.ts(2345)

dotenv type: https://github.com/motdotla/dotenv/blob/cf4c56957974efb7238ecaba6f16e0afa895c194/lib/main.d.ts#L107C1-L109C2

node.js built-in type:

interface ProcessEnv extends Dict<string> {}

interface Dict<T> {
    [key: string]: T | undefined;
}
mak3 commented 1 year ago

Ok, I learned that I can use "as" to workaround it.

dotenv.populate(process.env as dotenv.DotenvPopulateInput, parsed)