๐ŸŽ“ A1Learner
๐Ÿ”
0 of 37 lessons completed

TypeScript Global Augmentation

A declare global block inside a module file adds declarations to the global scope. The added declarations are visible in other files without an import.

The platform.d.ts file

The library declaration file declares a global Platform interface inside a declare global block. It also declares the currentPlatform function that the library exports.

declare global {
  interface Platform {
    name: string;
    version: string;
  }
}

export declare function currentPlatform(): Platform;

The platform.js file

The JavaScript library returns a platform object that already carries a region field at runtime. The declared type gains that field only through the augmentation.

export function currentPlatform() {
  return { name: "A1 OS", version: "2.0", region: "eu-west" };
}

The region.ts file

The region file is a module that extends the global Platform interface with a region member. Its helper reads the added member through the library function.

import { currentPlatform } from './platform';

declare global {
  interface Platform {
    region: string;
  }
}

export function platformRegion(): string {
  return currentPlatform().region;
}

Using the added member without an import

The consumer names the Platform type directly, with no import of the interface. The region member reads back because the augmentation merged it in.

import { currentPlatform } from './platform';
import { platformRegion } from './region';

const platform: Platform = currentPlatform();
console.log(platform.name);
console.log(platform.version);
console.log(platform.region);
console.log(platformRegion());

Example

import { currentPlatform } from './platform';
import { platformRegion } from './region';

const custom: Platform = { name: 'A1 OS', version: '3.0', region: 'us-east' };
console.log(custom.name + ' ' + custom.version);
console.log(custom.region);
console.log(platformRegion());
console.log(currentPlatform().name);

Key points

  • The declare global block sits inside a module file, and its declarations join the global scope.
  • An interface declared inside the block merges with a global interface of the same name.
  • Code in other files uses the added member without importing the interface.
  • The file that holds the block stays a module because it has its own imports and exports.

In this example, the consumer builds a Platform object literal with the augmented region member and never imports the Platform type. The literal is accepted because the declare global block merged region into the global interface.

Note

Global augmentation suits declarations that a library provides to every file, such as a platform description.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท TypeScript Playground

Exercise

How does a consumer use a member added by global augmentation?