Declare existing global variable in TypeScript
Question:
How to declare existing global variable in TypeScript? Answer:
declare const globalConfig;
Description:
Suppose you have a legacy code base for which you want to create a new TypeScript/React component. The legacy code already defines some global variables that you can access in the React code. For example:
<div>
<div id="app-container"></div>
<script>
const globalConfig = {
version: "5.0.2",
};
</script>
</div>
And the React component:
export const VersionInfo = () => {
return <div>Version: {globalConfig.version}</div>;
};
In the example above, the TypeScript compiler gives the following error message:
Unresolved variable or type globalConfig
This is legitimate since our TypeScript code knows nothing about the globalConfig
variable created by the legacy code. In this case, you can use the declare
keyword. You can use it to tell the TypeScript compiler that the variable exists.
declare const globalConfig: { version: string };
Reference:
TypeScript global variables reference
Share "How to declare existing global variable in TypeScript?"
Related snippets:
Tags:
declare, global, scope, variable, existing, legacy, code, typescript Technical term:
Declare existing global variable in TypeScript