Skip to content

Commit 6cf5141

Browse files
yunics-highfieldbluwysapphi-red
authored
feat(types): make ImportMetaEnv strictly available (#19077)
Co-authored-by: Bjorn Lu <[email protected]> Co-authored-by: sapphi-red <[email protected]>
1 parent ae91bd0 commit 6cf5141

File tree

3 files changed

+37
-1
lines changed

3 files changed

+37
-1
lines changed

docs/guide/env-and-mode.md

+6
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,12 @@ To achieve this, you can create an `vite-env.d.ts` in `src` directory, then augm
108108
```typescript [vite-env.d.ts]
109109
/// <reference types="vite/client" />
110110

111+
interface ViteTypeOptions {
112+
// By adding this line, you can make the type of ImportMetaEnv strict
113+
// to disallow unknown keys.
114+
// strictImportMetaEnv: unknown
115+
}
116+
111117
interface ImportMetaEnv {
112118
readonly VITE_APP_TITLE: string
113119
// more env variables...
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// This file tests `ViteTypeOptions` in `packages/vite/types/importMeta.d.ts`
2+
import type { ExpectFalse, ExpectTrue } from '@type-challenges/utils'
3+
4+
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
5+
interface TypeOptions1 {}
6+
interface TypeOptions2 {
7+
strictImportMetaEnv: unknown
8+
}
9+
interface TypeOptions3 {
10+
unknownKey: unknown
11+
}
12+
13+
type IsEnabled<Opts, Key extends string> = Key extends keyof Opts ? true : false
14+
15+
export type cases = [
16+
ExpectFalse<IsEnabled<TypeOptions1, 'strictImportMetaEnv'>>,
17+
ExpectTrue<IsEnabled<TypeOptions2, 'strictImportMetaEnv'>>,
18+
ExpectFalse<IsEnabled<TypeOptions3, 'strictImportMetaEnv'>>,
19+
]
20+
21+
export {}

packages/vite/types/importMeta.d.ts

+10-1
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,17 @@
22
// Thus cannot contain any top-level imports
33
// <https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation>
44

5+
// This is tested in `packages/vite/src/node/__tests_dts__/typeOptions.ts`
6+
// eslint-disable-next-line @typescript-eslint/no-empty-object-type -- to allow extending by users
7+
interface ViteTypeOptions {
8+
// strictImportMetaEnv: unknown
9+
}
10+
11+
type ImportMetaEnvFallbackKey =
12+
'strictImportMetaEnv' extends keyof ViteTypeOptions ? never : string
13+
514
interface ImportMetaEnv {
6-
[key: string]: any
15+
[key: ImportMetaEnvFallbackKey]: any
716
BASE_URL: string
817
MODE: string
918
DEV: boolean

0 commit comments

Comments
 (0)