Skip to content

Show examples of env.d.ts as a module #10945

Open
@thegatesdev

Description

@thegatesdev

📚 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!

Metadata

Metadata

Assignees

No one assigned

    Labels

    improve or update documentationEnhance / update existing documentation (e.g. add example, improve description, update for changes)

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions