Global declarations are used when you want to define types or variables that should be accessible everywhere in your project, without importing them in each file.
🧾 Use Cases
Declaring global variables, functions, or interfaces.
Adding custom types to the global
Window,NodeJS, orglobalobject.Setting types in environments like browsers or Node.js.
📁 How to Set Up
Create a file like
globals.d.tsor insidetypes/folder.Add the following to your
tsconfig.jsonso TypeScript knows about it:
{
"compilerOptions": {
"typeRoots": ["./types", "./node_modules/@types"]
},
"include": ["src", "types"] // or wherever your global types are
}🛠️ Declaring a Global Interface
// types/globals.d.ts
export {};
declare global {
interface MyGlobalSettings {
theme: "dark" | "light";
version: string;
}
var appSettings: MyGlobalSettings;
}Now you can use appSettings anywhere in your code:
console.log(appSettings.theme);🌐 Example: Global Window Extension
// types/globals.d.ts
export {};
declare global {
interface Window {
myAnalytics: () => void;
}
}Now window.myAnalytics() will be recognized by TypeScript.
💡 Global Constants and Functions
// types/globals.d.ts
export {};
declare global {
const __VERSION__: string;
function logInfo(msg: string): void;
}Use them globally:
console.log(__VERSION__);
logInfo("App started");🧩 Node.js Global Declaration
// types/globals.d.ts
export {};
declare global {
namespace NodeJS {
interface ProcessEnv {
NODE_ENV: "development" | "production";
API_KEY: string;
}
}
}✅ Best Practices
Wrap your declarations in
declare global { ... }.Always
export {}at the top to make the file a module, which ensures correct scope.Don’t pollute the global scope unnecessarily. Use it only for truly global values.