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

loadEnv return type mismatch #19173

Open
7 tasks done
michumk opened this issue Jan 9, 2025 · 1 comment
Open
7 tasks done

loadEnv return type mismatch #19173

michumk opened this issue Jan 9, 2025 · 1 comment

Comments

@michumk
Copy link

michumk commented Jan 9, 2025

Describe the bug

The loadEnv method currently declares its return type as Record<string, string>.
However, in practice, it returns undefined if we try to get env variable with key that doesn't exist.

import { loadEnv } from 'vite';

const env = loadEnv('', './');
const foo = env['XYZ']; // ts type inference marks `foo` as 'string'
console.log('foo value:', foo); // the value is actually 'undefined'

This assumption that all keys are always string might lead to potential runtime errors. Those errors could simply be avoided by forcing the if (value !== undefined) check with proper return type in loadEnv.

Proposed Fix:

Update the return type of loadEnv to Record<string, string | undefined> or Partial<Record<string, string>>.

I'm willing to submit a PR for this issue if solution is agreed on.


There is a similar issue, but for some reason the original author decided to close it after being asked to present an example and didn't describe the issue properly.
#18643

Reproduction

https://stackblitz.com/edit/vitejs-vite-qjnysz6r?file=vite.config.ts

Steps to reproduce

  1. Run npm install && npm run dev
  2. Check vite.config.ts and look at console output from dev command

Validations

@sapphi-red
Copy link
Member

This is how TypeScript works. You can enable that behavior by setting "noUncheckedIndexedAccess": true. I think Vite should keep the types as-is and let the user decide how they want to deal with it.

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

No branches or pull requests

2 participants