An issue arises when attempting to compile this simple try/catch block within a closure using TypeScript:
type TryCatchFn = (args: any, context: any) => void;
function try_catch(fn: TryCatchFn): TryCatchFn {
return (args, context) => void {
try {
throw new Error('Something bad happened');
} catch (e) {
console.log(e);
}
}
}
The compiler error message reads as follows:
data/src/cloud_scripts.ts:12:7 - error TS1005: ':' expected.
12 try {
~
data/src/cloud_scripts.ts:13:10 - error TS1005: ':' expected.
13 throw new Error('Something bad happened');
~~~
data/src/cloud_scripts.ts:13:45 - error TS1005: ',' expected.
13 throw new Error('Something bad happened');
~
data/src/cloud_scripts.ts:14:5 - error TS1005: ',' expected.
14 } catch (e) {
~~~~~
However, when the code is adjusted to remove the call to the fn function, the compilation succeeds without errors:
type TryCatchFn = (args: any, context: any) => void;
function try_catch(fn: TryCatchFn): void {
try {
throw new Error('Something bad happened');
} catch (e) {
console.log(e);
}
}
The revised version above sacrifices functionality for the sake of successful compilation. It poses the question of what might be going wrong in the initial implementation.