Categories
TypeScript Answers

How to add global types in TypeScript?

Spread the love

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.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.