“Augmentations for global scope can only be directly nested” in Typescript – How to fix it?

"Augmentations for global scope can only be directly nested" in Typescript

In this article we will share with some of solutions to fix the error “Augmentations for global scope can only be directly nested” in Typescript. So how to do it? Let’s go into detail now.

The reason for the error “Augmentations for global scope can only be directly nested” in Typescript

The error happens when you declare the global scope outside an external module.

Example of how the error happens:

declare global {
    type inforDetail = {
        name: string,
        age: number,
        date: string,
        Username: string,
        height: number,
        Eyecolor: string,
        address: string
    };
}

The error:

index.ts:1:9 - error TS2669: Augmentations for the global scope can only be directly nested in external modules or ambient module declarations.
1 declare global {
          ~~~~~~

Here I am trying to declare the inforDetail type in global scope, but I am declaring it outside of the external module so that I will get the error.

The solution for the error “Augmentations for global scope can only be directly nested” in Typescript

Change the file to the external module

The obvious solution here is to declare the global scope inside an external module. An external module is a file that contains import or export syntax. You can use the export keyword to change your file to an external module. The export keyword will help you to export some components that you want another file can use it. But you don’t have to export any component to make your file to an external module.

Example:

declare global {
    type inforDetail = {
        name: string,
        age: number,
        date: string,
        Username: string,
        height: number,
        Eyecolor: string,
        address: string
    };
}

export {};

Using an ambient module

Suppose I am using a third-party js library that provides the calcAge function, and I still want to use it safely in Typescript code. I can define an ambient module like this:

declare module personInfor {
    export class PersonDetail {
        calcAge(bornYear): number;
    }
}

Then I can include the ambient module into my typescript file by syntax:

// <reference path = "AmbientFileName.d.ts" /> which AmbientFileName here is index.d.ts
// <reference path = "./index.d.ts" />
const age1 = new personInfor();
console.log(age1.calcAge(2000));

Summary

In this article, I showed you how to solve the error “Augmentations for global scope can only be directly nested” in Typescript. You can only declare global scope in external modules with import or export statements or inside ambient modules. Let’s try these methoods!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *