I'm in the process of converting a large monolithic JavaScript application to TypeScript and am facing an issue regarding typing a specific module. I am seeking guidance on how to approach this particular problem.
It's important to note that I did not write the original code - my goal is to convert an existing application. Therefore, critiquing the JavaScript code itself will not be helpful
Here is the snippet of the original code for the module (thankfully it's short).
const CACHE_CONTROL_HEADERS = Symbol.for('cache control headers')
if (!global[CACHE_CONTROL_HEADERS]) {
global[CACHE_CONTROL_HEADERS] = [];
}
module.exports = global[CACHE_CONTROL_HEADERS];
I've learned that TypeScript does not support using symbols as index signatures, so I need to adjust the first line. Additionally, I believe I should change the last line to ES6 module format, resulting in the following:
const CACHE_CONTROL_HEADERS = (Symbol.for(
"cache control headers"
) as unknown) as string;
if (!global[CACHE_CONTROL_HEADERS]) {
global[CACHE_CONTROL_HEADERS] = [];
}
export default global[CACHE_CONTROL_HEADERS];
This modification has led to the following compile error:
index.ts:6:3 - error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Global & typeof globalThis'.
No index signature with a parameter of type 'string' was found on type 'Global & typeof globalThis'.
After some research, I have explored different methods to augment the type of the global object and tried adding the following code in a separate file alongside the module:
declare module NodeJS {
interface Global {
[key: string]: string;
}
}
Unfortunately, this didn't resolve the error, and my editor flagged additional issues with the index signature, such as:
Property 'Array' of type 'ArrayConstructor' is not assignable to string index type 'string[]'
At this point, I'm at a loss. If anyone can assist me in transforming this small file into TypeScript, I would greatly appreciate it!