Last updated: Feb 28, 2024
Reading time·3 min
To declare global types in TypeScript:
global.d.ts
file and declare types in the global namespace.export {}
.In the src
directory of your project, create a types
directory containing
the following global.d.ts
file.
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 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.
const emp: Employee = { id: 1, name: 'Bobby Hadz', salary: 100, }; console.log(emp); const person: Person = { name: 'Tom', age: 30, }; console.log(person);
I've also written an article on how to declare global variables in TS.
types
to your tsconfig.json
If you get an error in your IDE, try adding the path to your types
directory
to your tsconfig.json file.
{ "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.
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.
The location is determined by the include
and exclude
settings in your
tsconfig.json
file.
Here is an example that adds a removeLast
method to the global Array
interface. This is the global.d.ts
file.
export {}; declare global { interface Array<T> { removeLast(): T[]; } }
And here is how we add the method to the prototype and use it.
if (!Array.prototype.removeLast) { Array.prototype.removeLast = function () { this.pop(); return this; }; } const arr = ['a', 'b', 'c']; arr.removeLast(); console.log(arr); // 👉️ ['a', 'b']
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.
You can learn more about the related topics by checking out the following tutorials: