Global Augmentation Extends The Window Type

Augment the built-in Window interface with declare global, add typed application fields, and read them through a narrowed global scope.

TypescriptConfig Management

Code

typescriptsnippet
31 lines
export {};

// Global augmentation: 给内置 Window 接口合并应用字段
declare global {
  interface Window {
    appStage: 'development' | 'production';
    appRegion?: string;
  }
}

const scope = globalThis as unknown as Window;

scope.appStage = 'production';
scope.appRegion = 'eu-west-1';

function stage(): 'development' | 'production' {
  return scope.appStage;
}

function region(): string {
  return scope.appRegion ?? 'us-east-1';
}

console.log('stage:', stage());
console.log('region:', region());

// 字段名拼错会在编译期被拒绝
// scope.appStageTypo = 'production';

const keys: Array<keyof Window> = ['appStage', 'appRegion'];
console.log('tracked keys:', keys.join(','));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

stage: production
region: eu-west-1
tracked keys: appStage,appRegion

How it works

Global Augmentation Extends The Window Type is built around the functions stage and region.

Using it

The primary signature is function stage()

The demo output is labeled (stage:, region:, tracked keys:), so every printed line traces back to the operation behind it.

Key statements

return scope.appRegion ?? 'us-east-1';

Interactive Tools for This Topic

FAQ

Does this work in a bare project with no dependencies file?
Yes — a bare project runs it as-is, since nothing needs declaring. The file defines `stage`, `region` at load time.