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.
Code
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,appRegionHow 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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.