Skip to content

The ambient world

Relay’s release script builds one bundle and stamps it. The bundler replaces __RELAY_VERSION__ and __BUILD_TIME__ with string literals, so the startup log can say which build is running. In the source they look like variables nobody declared. tsc reports Cannot find name '__RELAY_VERSION__', and the usual fix, a cast or // @ts-ignore, turns off the check for that line.

The right fix is to tell the compiler that the name exists. This lesson covers how: declare, what makes a file global or local, and which settings decide what is in scope before you write a line.

declare says “this exists at runtime, trust me” and emits no code. It adds a name to the type world only:

declare const __RELAY_VERSION__: string
declare function gtag(event: string): void
declare class LegacyQueue {
size(): number
}
export const banner: string = `relay ${__RELAY_VERSION__}`
export const n: number = new LegacyQueue().size()
gtag("start")

Nothing checks the claim. If the bundler does not define __RELAY_VERSION__, the build passes and the program throws a ReferenceError at startup. The declaration is only as true as your build. That is why the exercise below keeps declarations few and puts them in one file.

TypeScript treats a file as a module if it has a top-level import or export. Any other file is a script, and its top-level names go into the global scope. For .d.ts files this is the difference between a declaration that works and one that does nothing:

globals.d.ts (a script: no import or export)
declare const __BUILD_TIME__: string
globals.d.ts (a module: the names stay inside)
export {}
declare const __BUILD_TIME__: string // not visible to other files

A single export {} is enough to turn a global declaration into a private one, and the error you get in another file is Cannot find name, which does not hint at the cause. If a global declaration seems to be ignored, look for a stray import or export first. The course’s moduleDetection: "force" (lesson 1 of M1) makes every .ts file a module, but it never applies to .d.ts files, which are scripts unless they import or export.

A module that needs both an import and a global uses declare global. Its body is added to the global scope:

import type { Server } from "bun"
declare global {
const __RELAY_VERSION__: string
var relayServer: Server<undefined> | undefined
namespace NodeJS {
interface ProcessEnv {
RELAY_PORT?: string
}
}
}
export const port: string | undefined = process.env.RELAY_PORT

The same rule as in M4’s augmentation lesson holds: the file must be a module for declare global to be allowed. Use var for a global that can be assigned, because let and const are not properties of globalThis.

Where does process.env come from? From @types/node, which @types/bun pulls in. Its type has an index signature: every key is string | undefined, so a typo like process.env.RELAY_PROT compiles. Bun’s types make ProcessEnv extend Bun.Env, an interface made to be extended, and Bun.env uses the same one. Extending either, from a script file, adds your keys to both:

globals.d.ts
declare namespace NodeJS {
interface ProcessEnv {
RELAY_LOG?: "debug" | "info" | "warn" | "error"
}
}

After this, process.env.RELAY_LOG has the union type in every file of the program.

Be honest about what this does. The declaration gives you autocomplete and a precise type, but nothing validates the value at runtime: RELAY_LOG=verbose is still a string. Keep the loader from M1 that checks it, and treat the declaration as the promise that the loader makes.

Three settings decide what is in scope before any file of yours is read.

  • lib selects the language and platform declarations that ship with tsc: es2023, dom, webworker. Without lib, target picks a default that includes dom, so document type-checks in a server project. Set lib to ["esnext"] and document becomes an error, which is what you want for Relay.
  • types lists packages from node_modules/@types (or typeRoots) whose globals are loaded. In this course’s tsc (TypeScript 7) the default is an empty list: with no types setting, Bun and process are “not found”. Relay’s tsconfig says "types": ["bun"], which loads @types/bun, and that loads bun-types.
  • typeRoots changes the folders searched for types, from node_modules/@types to wherever you put them.

You can see each source by turning one off. The probe is a file that uses Bun, process, fetch and document:

Terminal window
tsc --noEmit --types bun # all four resolve (the default lib includes dom)
tsc --noEmit --types bun --lib es2023 # only `document` fails: Cannot find name 'document'
tsc --noEmit --types node # `Bun` fails: Cannot find name 'Bun'
tsc --noEmit --lib es2023 --types "" # all four fail

fetch resolves in the first three cases, from different places: the DOM lib in the first, bun-types in the second, @types/node in the third. So a global can have more than one source, and removing one setting does not always remove the name.

To put your own globals in a package that other projects share, make a folder types/relay-env/index.d.ts, set "typeRoots": ["./types", "./node_modules/@types"], and add "relay-env" to types. A file can also pull in a package locally with /// <reference types="bun" />. It is the old way of doing what types does, and you still see it at the top of generated .d.ts files.

Copy these files into the Relay project from lesson 1 of M1, in one folder such as src/declarations/ambient/. Rename globals.starter.d.ts to globals.d.ts and main.starter.ts to main.ts. Fill in globals.d.ts so that the project type-checks, then run bun test in that folder. The test runs tsc on globals.d.ts, main.ts and misuse.ts and expects no errors.

globals.d.ts
// Relay's bundler replaces two names at build time:
// bun build --define __RELAY_VERSION__='"1.4.0"' --define __BUILD_TIME__='"2026-03-01T09:00:00Z"'
// and the deploy script sets two environment variables.
//
// Declare them so main.ts and misuse.ts type-check. Rules:
// - __RELAY_VERSION__ and __BUILD_TIME__ are global constants of type string.
// - process.env.RELAY_PORT is `string | undefined`.
// - process.env.RELAY_LOG is `"debug" | "info" | "warn" | "error" | undefined`.
// - Keep this file a script (no import or export), or the top-level declarations stop being global.
main.ts
export type LogLevel = "debug" | "info" | "warn" | "error"
export function banner(): string {
return `relay ${__RELAY_VERSION__} (built ${__BUILD_TIME__})`
}
export function readLevel(): LogLevel {
return process.env.RELAY_LOG ?? "info"
}
export function readPort(): number {
return Number(process.env.RELAY_PORT ?? "8080")
}
misuse.ts
import { readLevel } from "./main.ts"
// @ts-expect-error: a build-time constant is read-only
__RELAY_VERSION__ = "9.9.9"
// @ts-expect-error: __BUILD_TIME__ is an ISO string, not a number
export const built: number = __BUILD_TIME__
// @ts-expect-error: RELAY_LOG is a level name, not any string
export const level: "debug" = process.env.RELAY_LOG
// @ts-expect-error: readLevel() returns a LogLevel, never a number
export const bad: number = readLevel()
main.test.ts
import { afterEach, expect, test } from "bun:test"
import { existsSync } from "node:fs"
import { join } from "node:path"
import { banner, readLevel, readPort } from "./main.ts"
const tsc =
[join(import.meta.dir, "../../../node_modules/.bin/tsc"), join(process.cwd(), "node_modules/.bin/tsc")].find(existsSync) ?? "tsc"
function check(files: string[]): { code: number; out: string } {
const r = Bun.spawnSync(
[tsc, "--noEmit", "--strict", "--target", "esnext", "--module", "esnext", "--moduleResolution", "bundler",
"--verbatimModuleSyntax", "--allowImportingTsExtensions", "--skipLibCheck", "--ignoreConfig", "--types", "bun", ...files],
{ cwd: import.meta.dir }
)
return { code: r.exitCode, out: r.stdout.toString() + r.stderr.toString() }
}
const g = globalThis as Record<string, unknown>
afterEach(() => {
delete g.__RELAY_VERSION__
delete g.__BUILD_TIME__
delete process.env.RELAY_LOG
delete process.env.RELAY_PORT
})
test("globals.d.ts makes main.ts and misuse.ts type-check", () => {
const r = check(["globals.d.ts", "main.ts", "misuse.ts"])
expect(r.out).toBe("")
expect(r.code).toBe(0)
})
test("banner reads the injected constants", () => {
g.__RELAY_VERSION__ = "1.4.0"
g.__BUILD_TIME__ = "2026-03-01T09:00:00Z"
expect(banner()).toBe("relay 1.4.0 (built 2026-03-01T09:00:00Z)")
})
test("readLevel defaults to info and reads RELAY_LOG", () => {
expect(readLevel()).toBe("info")
process.env.RELAY_LOG = "debug"
expect(readLevel()).toBe("debug")
})
test("readPort defaults to 8080 and reads RELAY_PORT", () => {
expect(readPort()).toBe(8080)
process.env.RELAY_PORT = "9000"
expect(readPort()).toBe(9000)
})

misuse.ts has four lines that must stay errors. If you declare __RELAY_VERSION__ with var, or give RELAY_LOG the type string, one of the @ts-expect-error lines stops being an error, and tsc reports it.

  • declare adds a name to the type world and emits nothing. It is a promise about the runtime.
  • A .d.ts with a top-level import or export is a module, and its declarations are not global. Use declare global there.
  • Extend NodeJS.ProcessEnv or Bun.Env to type your environment keys, and still validate the values.
  • lib picks the platform declarations, types picks the @types packages (empty by default in TypeScript 7), typeRoots picks where to look.
  • Keep globals few, prefixed, and in one file.