[Typescript] Using Variables Declared Elsewhere
The declare
keyword in TypeScript allows you to specify types for global variables. Whenever you use it, an ambient context is created, which means that the variable is injected without needing to provide an implementation.
Here's how we would use declare
to specify the type for DEBUG
, which we'll type as an empty object for now:
declare const DEBUG: {};
This tells TypeScript that DEBUG
is a constant that doesn't need to provide an implementation.
declare const DEBUG: {
getState: () => {
id: string;
};
};
const state = DEBUG.getState(); // red squiggly line under getState
type test = Expect<Equal<typeof state, { id: string }>>;
How to use this declarion in anothe file?
1. Create a .d.ts
file
declare const DEBUG: {
getState: () => {
id: string;
};
};
Then DEBUG
is globally available
2. use declare global
If we don't create a .d.ts
file, we can use
declare global {
const DEBUG: {
getState: () => {
id: string;
};
};
};