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

ImportMetaEnv's [key: string] should be unknown for type safety #19376

Open
4 tasks done
Samuel-Therrien-Beslogic opened this issue Feb 6, 2025 · 2 comments
Open
4 tasks done

Comments

@Samuel-Therrien-Beslogic
Copy link

Samuel-Therrien-Beslogic commented Feb 6, 2025

Description

Using a custom env variable will by default be typed as any. To have the correct type, one has to use module augmentation. This is intended and working fine.

But even when you augment a value correctly, you are not protected against forgetting to add more, or mistyping the value.

/// <reference types="vite/client" />

interface ImportMetaEnv {
  readonly VITE_CORRECT: string;
}
import.meta.env.VITE_MISTYPED.at(1) // oops! Accepted by typescript! (some type-aware linters may warn)

Unfortunately, module augmentation doesn't seem to work since the index signature was already set ! So I can't simply opt-in to:

/// <reference types="vite/client" />

interface ImportMetaEnv {
  [key: string]: unknown
  readonly VITE_CORRECT: string;
}
import.meta.env.VITE_MISTYPED.at(1) // VITE_MISTYPED is still any :(

Hence, I am requesting for ImportMetaEnv to default to unknown, which is more accurate, more type-safe, and would promote adding used variables in ImportMetaEnv module augmentation.

Suggested solution

ImportMetaEnv should have [key: string]: unknown instead of [key: string]: any

Alternative

Using https://www.npmjs.com/package/patch-package to patch vite's source code on install.

Discover or request some way for module augmentation to override existing declarations.

Not include any index signature in ImportMetaEnv, and document that the dev should add one themselves based on the strictness they want.

Additional context

Relevant ongoing typescript conversations:

Validations

@bluwy
Copy link
Member

bluwy commented Feb 7, 2025

related #19077

@Samuel-Therrien-Beslogic
Copy link
Author

Samuel-Therrien-Beslogic commented Feb 11, 2025

Hmm, a different approach but I think it would work as well.

My intuition tells me the conditional type should be done on any/unknown (any being the escape hatch), but I don't feel too strongly about it.

If that goes through, I'll have to ensure that my teams remember to use type ViteStrictImportMetaEnv = true

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

3 participants