QA Interview Hub · Knowledge base · Quizzes · Українська

TypeScript › Modules and tsconfig

Environment types, .d.ts and environment variables

A .d.ts file contains only type declarations without code, and process.env has type string | undefined because a variable may really be missing. So variables are read through one module that validates them (with a function or a schema such as zod) and fails with a clear message. Extending ProcessEnv or using the ! operator only removes undefined for the compiler and checks nothing at runtime.

TypeScript · Modules and config

CI did not set BASE_URL and the test opened the page «undefined/login». Why did TypeScript stay silent?

The new BASE_URL variable was added locally in .env and forgotten in CI. The run did not fail at the start: the test opened the address undefined/login relative to the config baseURL and failed a minute later with an unclear timeout. The code had process.env.BASE_URL!, so the compiler was silent. The topic of this lesson is what exactly TypeScript knows about the environment (variables, global objects, libraries without types) and how to make a missing variable break the test at once with a clear message.

How it works and why. .d.ts files contain only type declarations, without code: they describe what exists somewhere else. They come from @types/... packages (for example @types/node describes process), from the libraries themselves, or are written by hand for JS packages without types and to extend existing ones. Which global type packages are visible is set by the types option in tsconfig: since TypeScript 6.0 it is empty by default, so "types": ["node"] must be listed explicitly, otherwise process gives TS2591.

The type of process.env is a dictionary where every value is string | undefined. That is honest: the variable may really be missing. All the ways to «make the type more convenient» simply remove undefined without any guarantee:

const url = process.env.BASE_URL!;           // "!" says: there is surely a value here
await page.goto(url + '/login');
// if the variable is missing url is undefined and the page is "undefined/login"
// env.d.ts: extending the type
declare global {
  namespace NodeJS {
    interface ProcessEnv {
      BASE_URL: string;
    }
  }
}
export {};
// now process.env.BASE_URL is string while CI may not have the variable

Three ways to get an environment variable

Wrong

! or extending ProcessEnv

The type says string while at runtime it may be undefined. The error shows up late and far from the cause.

Right

A module with a check or a schema

Reading and checking in one place: the test fails at the start with the variable name and the rest of the code gets a ready string.

Figure 1. Extending a type only tells the compiler «the variable exists»; only code can check that.

Example: a module with a check. One module reads the variables, checks them and hands out a typed object. All tests import env from here and do not touch process.env directly:

// src/env.ts
function required(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error('Missing env variable ' + name);
  return value;
}

export const env = {
  baseUrl: required('BASE_URL'),
  apiToken: required('API_TOKEN'),
  timeoutMs: Number(process.env.TIMEOUT_MS ?? '30000'),
} as const;

Now without the variable the run fails at once: «Missing env variable BASE_URL». Even better is checking with a schema: zod converts types right away (z.coerce.number()) and derives the type from it.

import { z } from 'zod';

const schema = z.object({
  BASE_URL: z.url(),
  API_TOKEN: z.string().min(1),
  TIMEOUT_MS: z.coerce.number().int().positive().default(30_000),
});

export const env = schema.parse(process.env);
// env.TIMEOUT_MS: number, env.BASE_URL: string

Where the variables come from: dotenv in playwright.config.ts, and in modern Node also the built-in --env-file flag and the process.loadEnvFile() method. In CI they are set as secrets or pipeline variables and not through a file.

node --env-file=.env.ci run-tests.ts   # Node reads .env itself

Your own .d.ts: when and why. Extending a global type, for example window.appReady, is declared in a module file through declare global (hence export {} at the end):

// types/global.d.ts: a module file, hence export {}
declare global {
  interface Window {
    appReady?: boolean;
  }
}
export {};

// in a test
await page.waitForFunction(() => window.appReady === true);

For a JS library without types a minimal module declaration is enough. Here, on the contrary, the file must not be a module, that is no import/export, otherwise it becomes an augmentation of an existing module:

// types/legacy-lib.d.ts: a file WITHOUT import/export, this declares a module
declare module 'legacy-lib' {
  export function parse(input: string): number;
}

Limits and alternatives. With skipLibCheck: true the compiler checks no .d.ts files at all, including your own, so errors in them may go unnoticed. If one repository has both Cypress and Jest, their global describe, it and expect clash, and then separate tsconfigs are set up for different parts: a base tsconfig.base.json and configs for e2e, API tests and utilities that inherit it through extends and set types and include themselves:

{
  "extends": "./tsconfig.base.json",
  "compilerOptions": { "types": ["node"] },
  "include": ["e2e"]
}

This is exactly inheritance of settings. Project references (references and composite) are needed for something else, a linked build of several projects.

Common mistakes.

  • process.env.X! scattered across tests: a missing variable shows up far from the cause.
  • Extending ProcessEnv instead of checking: the type claims string although the variable may be missing.
  • Number(process.env.TIMEOUT_MS) without a default: an empty variable gives NaN or 0.
  • A file with declare module 'lib' that has an import: this is an augmentation, not a declaration, and the compiler complains the module cannot be found.
  • Secrets in a .env in the repository: the file goes in .gitignore and in CI they are set as secrets.

Check yourself

Why does extending ProcessEnv through declare global not protect against failing with undefined in a URL?

Answer

It is only a claim for the compiler and nothing is checked at runtime. If the variable is missing the value is still undefined while the type promises string. The check has to be written in code: a required function or a schema.

A custom global.d.ts contains declare global { interface Window { appReady?: boolean } } but window.appReady is still not found. What to check?

Answer

First, whether the file is a module (export {} is needed, otherwise declare global is not allowed), second, whether it falls into the tsconfig include, third, whether the project includes the DOM library (lib) that has Window.

In an interview. Junior: .d.ts files contain only types. process.env is string | undefined, so I read variables through a module that checks them and fails with a clear message if one is missing. Middle/Senior: I do not extend ProcessEnv and do not use ! because that removes undefined without a check. I validate with a schema (zod) that also converts types. For different parts of a repository I make separate tsconfigs through extends with their own types, and I remember skipLibCheck as the reason errors in my own .d.ts files may go unnoticed.

More articles in this chapter