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

Should error whenever an unvalidated env variable is used #27

Open
BrunnerLivio opened this issue May 16, 2024 · 1 comment
Open

Should error whenever an unvalidated env variable is used #27

BrunnerLivio opened this issue May 16, 2024 · 1 comment

Comments

@BrunnerLivio
Copy link

I am looking for a way to ONLY allow using env variables that are defined in my env.ts schema.

As an example:

env.ts

import {defineConfig} from '@julr/vite-plugin-validate-env'
import {z} from 'zod'

export default defineConfig({
  validator: 'zod',
  schema: {
    VITE_LANGUAGE: z.string(),
  },
})

In the application code, the following should occur (desired behavior)

src/app.ts

// ✅ TypeScript: type "string", all good!
import.meta.env.VITE_LANGUAGE

// ❌ TypeScript: Key "VITE_WHATEVER" does not exist
import.meta.env.VITE_WHATEVER
@BrunnerLivio
Copy link
Author

BrunnerLivio commented May 16, 2024

I am aware this is not directly related to this library but rather to Vite's typing of ImportMetaEnv (see below). Feel free to close if you think this should not be discussed as part of this project. However I think it would be worth adding a documentation entry in this project's README if we'd find a solution for this - hence why I created an issue here.

node_modules/vite/types/importMeta.d.ts

interface ImportMetaEnv {
  [key: string]: any
  BASE_URL: string
  MODE: string
  DEV: boolean
  PROD: boolean
  SSR: boolean
}

Vite seems to add [key: string]: any as a default. I wonder whether there is a way we could overwrite that. Since we have to use an interface to augment ImportMetaEnv and to make the module augmentation work I am not too sure how though.

I've already tried the following without avail:

env.d.ts

type ImportMetaEnvAugmented =
  import('@julr/vite-plugin-validate-env').ImportMetaEnvAugmented<
    typeof import('./src/env').default
  >

interface ImportMetaEnv extends ImportMetaEnvAugmented {
  [key: string]: never
}

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

No branches or pull requests

1 participant