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

fix(types): replace any with unknown in ImportMetaEnv for type safety #19508

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

Antraxmin
Copy link

Description

This PR replaces [key: string]: any; with [key: string]: unknown; in ImportMetaEnv to improve type safety.
Using any disables TypeScript's type checking, which can lead to unintended runtime errors.
By switching to unknown, we enforce explicit type handling while maintaining flexibility.

If necessary, we can update the documentation in guide/env-and-mode.md with helper functions to improve DX, based on Maintainer feedback.

Fixes: #19376

What problem does this PR solve?

  • any allows invalid operations (e.g., import.meta.env.VITE_API_URL.at(1), import.meta.env.VITE_PORT * 2).
  • There is no enforcement for missing environment variables, leading to potential undefined access issues.
  • unknown requires explicit type assertions, preventing unintended misuse and improving type safety.

Changes

  • Replaced any with unknown in ImportMetaEnv (packages/vite/types/importMeta.d.ts).
  • No breaking changes → Developers will now need to explicitly cast types when accessing import.meta.env.

Alternatives considered

  • Keeping any → ❌ Weak type safety, potential runtime issues.
  • Using string | number | boolean | undefined; → ❌ .env files store values as strings, making automatic inference unreliable.
  • Using unknown (✅ Best approach) → Ensures safety while allowing explicit type handling.

Additional context

  • Maintainer feedback is welcome regarding whether I can also update the documentation with best-practice helper functions.

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

Successfully merging this pull request may close these issues.

1 participant