Description
📚 Subject area/topic
TypeScript support, middleware, environment variables
📋 Page(s) affected (or suggested, for new content)
https://docs.astro.build/en/guides/environment-variables/#intellisense-for-typescript
https://docs.astro.build/en/guides/middleware/#middleware-types
📋 Description of content that is out-of-date or incorrect
The documentation examples show the env.d.ts
file as being a normal TypeScript file, not a module.
This caused two problems for me:
1: To get the types in this file to actually apply, I had to add the "src" directory to the tsconfig "include" paths:
- "include": [".astro/types.d.ts", "**/*"],
+ "include": [".astro/types.d.ts", "**/*", "src"],
It looks like non-module scripts are not automatically included otherwise. Although I often see "src/**/*" being used, which also solves this problem, using "**/*" is the default in Astro.
2: You cannot import types from other modules using the import { ... } from
syntax. This is not really a problem for environment variable definitions, because they don't include complex types. But it's a different story with context locals:
namespace App {
interface Locals {
myLocalType: LocalType<unknown>;
}
}
Having the above definition and using Astro.locals.myLocalType
fails to get the correct type (and thus gives me ESLint warnings) because it isn't imported.
I suggest changing the examples so that this file becomes a module by default, just like the following example:
import type { LocalType } from "@bar/foo";
declare global {
interface ImportMetaEnv {
readonly MY_VARIABLE: string;
}
interface ImportMeta {
readonly env: ImportMetaEnv;
}
namespace App {
interface Locals {
myLocalType: LocalType<unknown>;
}
}
}
Thank you!