How to declare global types in TypeScript

avatar

Borislav Hadzhiev

Sun Mar 20 20222 min read

Declare global types in TypeScript #

To declare global types in TypeScript:

  1. Create a global.d.ts file and declare types in the global namespace.
  2. Add types or interfaces that need to be globally accessible.
  3. Make the file a module by using export {}.

In the src directory of your project, create a types directory containing the following global.d.ts file.

src/types/global.d.ts
export {}; declare global { /** * Now declare things that go in the global namespace, * or augment existing declarations in the global namespace. */ interface Employee { id: number; name: string; salary: number; } type Person = { name: string; age: number; }; }

The example above shows how to create a module that modifies the global namespace. We created a globally accessible Employee and Person types.

Now I can access the types in my project without having to import them.

index.ts
const emp: Employee = { id: 1, name: 'James', salary: 100, }; console.log(emp); const person: Person = { name: 'Tom', age: 30, }; console.log(person);
Make sure to adjust the names of the types and their key-value pairs according to your use case.

If you are getting an error in your IDE, try adding the path to your types directory to your tsconfig.json file.

tsconfig.json
{ "compilerOptions": { // ... rest "typeRoots": ["./node_modules/@types", "./src/types"] } }

We used the export {} line in our global.d.ts file to mark it as an external module. A module is a file that contains at least 1 import or export statement. We are required to do that to be able to augment the global scope.

You only need the export line if your .d.ts file exports nothing. Otherwise, you can remove it.

TypeScript looks for .d.ts files in the same places it looks for your regular .ts files, which is determined by the include and exclude settings in your tsconfig.json file.

You can also use this approach to augment existing declarations in the global namespace.

Here is an example that adds a removeLast method to the global Array interface. This is the global.d.ts file.

src/types/global.d.ts
export {}; declare global { interface Array<T> { removeLast(): T[]; } }

And here is how we add the method on the prototype and use it.

index.ts
if (!Array.prototype.removeLast) { Array.prototype.removeLast = function () { this.pop(); return this; }; } const arr = ['a', 'b', 'c']; arr.removeLast(); console.log(arr); // 👉️ ['a', 'b']
Note that you have to add the method to Array.prototype in a file that runs before all other files, e.g. an index.ts file.

If you try to use the method before it was added to the prototype you'd get an error.

TypeScript will merge the declared from you Array interface with the original Array interface, so when you use the arrays, you will be able to access methods and properties from both interfaces.

Use the search field on my Home Page to filter through my more than 1,000 articles.