闭包中的尝试/捕获会给出错误



闭包中的这个简单的尝试/捕获在使用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);
}
}
}

输出为:

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) {
~~~~~

但是,如果我重写它以不调用 fn 函数,则没有错误:

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);
}
}

显然,上面的重写破坏了该功能。我只是好奇在第一种情况下我做错了什么。

箭头函数的返回类型的类型注释必须位于参数列表之后和=>之前:

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);
}
}
}

或者,您可以完全省略返回类型:

function try_catch(fn: TryCatchFn): TryCatchFn {
return (args, context) => {
try {
throw new Error('Something bad happened');
} catch (e) {
console.log(e);
}
}
}

当你写:

return (args, context) => void { ... }

这被解释为具有表达式主体的箭头函数。void运算符计算以下表达式,然后将结果抛弃,因此这是一个返回undefined的函数。本例中的表达式是对象文本,try在对象文本中无效。

没有void

return (args, context) => { ... }

将是带有块语句正文的箭头函数。您的try在这里可以正常工作。如果你没有从块中返回任何内容,你不需要显式给出返回类型,但如果你愿意,你可以:

return (args, context): void => { ... }

相关内容

最新更新