【问题标题】:What is the correct jsdoc type annotation for a try..catch identifier?try..catch 标识符的正确 jsdoc 类型注释是什么?
【发布时间】:2020-05-26 14:52:30
【问题描述】:

在使用 JSDoc cmets 注释 JavaScript 源代码时,如何注释 try..catch 标识符的类型?

try {
  throw new Error();
} catch (whatIsMyType) {
  console.error(whatIsMyType.message);
}

我特别要求TypeScript JSDoc dialect,但Closure Compiler dialect 甚至JSDoc itself 的答案会很有见地。

我试过(对于 TypeScript):

try { throw new Error(); } catch (/** @type {Error} */ e) {/*...*/}
try { throw new Error(); } /** @param {Error} e*/ catch (e) {/*...*/}
/** @param {Error} e*/ try { throw new Error(); } catch (e) {/*...*/}

但没有成功。 e 始终键入 any。什么会起作用

try { throw new Error(); } catch (_e) {
  /** @type {Error} */
  var e = _e;
  // ...
}

额外的变量会被闭包编译器的高级模式优化掉,但我发现从性能的角度来看(在开发版本中)很麻烦而且不是最优的,希望有更好的方法(即我没有的方法)必须创建一个人工变量来注释正确的类型)。

【问题讨论】:

    标签: javascript typescript google-closure-compiler jsdoc


    【解决方案1】:
    try {throw new Error();} catch (/** @type {Error}*/whatIsMyType) {
      console.error(whatIsMyType.message);
    }
    

    根据Closure Compiler有效。

    我写的打字稿不多,但我浏览了几个来源,大多看不到catch 级别的注释。我做的几个see看起来是这样的;

    try { throw new Error(); } catch (e: Error) {}
    

    更新:

    我认为 TypeScript 拒绝保证 check 块的类型是正确的。您可以在try 块中抛出任何东西(有意或无意),因此编译器无法确保捕获的捕获是正确的类型。在a related answer 中,解决方案是您应该检查catch 中的类型:

    try {
      throw new CustomError();
    }
    catch (err) {
      console.log('bing');
      if (err instanceof CustomError) {
        console.log(err.aPropThatIndeedExistsInCustomError); //works
        console.log(err.aPropThatDoesNotExistInCustomError); //error as expected
      } else {
        console.log(err); // this could still happen
      }
    }
    

    credit for ☝?

    而且我(和Robert Martin)鼓励这种类型的检查,即使是强类型。

    更新 2

    我已经将上面的示例重写为闭包编译器语法,我相信这一点仍然有效。即使 Closure 允许您从第一个示例中进行定义,您也可能不想(或至少,不仅如此):

    class CustomError extends Error {
      constructor() {
        super();
        /** @type {string} */
        this.aPropThatIndeedExistsInCustomError = '';
        throw new Error('Not so fast!');  // The evil part is here
      }
    }
    
    
    try {
      throw new CustomError();
    }
    catch (/**  @type {CustomError} */err) {
      console.log('bing');
      if (err instanceof CustomError) {
        console.log(err.aPropThatIndeedExistsInCustomError); //works
        console.log(err.aPropThatDoesNotExistInCustomError); //error as expected
      } else {
        console.log(err); // this could still happen
      }
    }
    

    on closure-compiler.appspot

    【讨论】:

    • Catch 子句在 TypeScript 中不能有类型注解。该示例是一个 promise catch 处理程序,它具有不同的语义,因为它是一个函数参数。
    • 感谢 @Graham 提供 Closure Compiler 解决方案。 @Jake 所以没有办法用 TypeScript 做到这一点?悲伤,但可以理解……
    猜你喜欢
    • 2013-03-08
    • 1970-01-01
    • 2023-04-09
    • 2014-12-01
    • 2015-06-02
    • 2013-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多