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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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