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: a type without a value
Section titled “declare: a type without a value”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__: stringdeclare function gtag(event: string): voiddeclare 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.
Script files and module files
Section titled “Script files and module files”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:
declare const __BUILD_TIME__: stringexport {}declare const __BUILD_TIME__: string // not visible to other filesA 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.
declare global
Section titled “declare global”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_PORTThe 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.
process.env and Bun.env
Section titled “process.env and Bun.env”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:
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.
Where the built-in names come from
Section titled “Where the built-in names come from”Three settings decide what is in scope before any file of yours is read.
libselects the language and platform declarations that ship withtsc:es2023,dom,webworker. Withoutlib,targetpicks a default that includesdom, sodocumenttype-checks in a server project. Setlibto["esnext"]anddocumentbecomes an error, which is what you want for Relay.typeslists packages fromnode_modules/@types(ortypeRoots) whose globals are loaded. In this course’stsc(TypeScript 7) the default is an empty list: with notypessetting,Bunandprocessare “not found”. Relay’s tsconfig says"types": ["bun"], which loads@types/bun, and that loadsbun-types.typeRootschanges the folders searched fortypes, fromnode_modules/@typesto 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:
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 failfetch 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.
Exercise
Section titled “Exercise”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.
// 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.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")}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 numberexport const built: number = __BUILD_TIME__
// @ts-expect-error: RELAY_LOG is a level name, not any stringexport const level: "debug" = process.env.RELAY_LOG
// @ts-expect-error: readLevel() returns a LogLevel, never a numberexport const bad: number = readLevel()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.
declareadds a name to the type world and emits nothing. It is a promise about the runtime.- A
.d.tswith a top-levelimportorexportis a module, and its declarations are not global. Usedeclare globalthere. - Extend
NodeJS.ProcessEnvorBun.Envto type your environment keys, and still validate the values. libpicks the platform declarations,typespicks the@typespackages (empty by default in TypeScript 7),typeRootspicks where to look.- Keep globals few, prefixed, and in one file.
Further reading
Section titled “Further reading”- TypeScript handbook: Modules reference, ambient modules: declare module, pattern modules, and when it becomes an augmentation.
- TSConfig reference: types: which @types packages add globals.
- TypeScript handbook: Declaration Files, by example: declare for functions, variables and namespaces.