How to add global types in TypeScript?

Sometimes, we want to add global types in TypeScript.

In this article, we’ll look at how to add global types in TypeScript.

How to add global types in TypeScript?

To add global types in TypeScript, we can add the declare global statement in a .d.ts file.

For instance, we write

declare global {
  interface String {
    fancyFormat(opts: StringFormatOptions): string;
  }
}

to add the String interface into the global type declaration to add the fancyFormat method to a string object.

We specify the signature of it with (opts: StringFormatOptions) and we specify that it returns a string.

Conclusion

To add global types in TypeScript, we can add the declare global statement in a .d.ts file.