During the process of converting a codebase to TypeScript, I encountered something unfamiliar. In particular, there are two functions with what appear to be class-like variables within them. The following function is one that caught my attention:
const wait = (ms) =>
new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => {
delete wait.reject;
resolve();
}, ms);
wait.reject = (reason) => {
clearTimeout(timeoutId);
reject(reason);
};
});
As you can observe, it contains a variable called wait.reject
, which is an arrow function defined at the end. Despite deleting the reject variable after a certain time duration.
To incorporate typing for this scenario, I resorted to using (wait as { reject: ... }.reject
, as shown below:
const wait = (ms: number) =>
new Promise<void>((resolve, reject) => {
const timeoutId = setTimeout(() => {
delete (wait as { reject?: () => void }).reject;
resolve();
}, ms);
(wait as { reject?: (reason: string) => void }).reject = (reason: string) => {
clearTimeout(timeoutId);
reject(reason);
};
});
Naturally, relying on as
is not the most favorable approach. Is there anyone who knows the correct way to type this? This issue extends beyond just one function in the codebase.
Your assistance and insights are greatly appreciated! :)