【问题标题】:Returning a typed let value from Typescript async await method?从 Typescript async await 方法返回一个类型化的 let 值?
【发布时间】:2017-12-20 17:06:47
【问题描述】:

我的命令行应用程序的主文件中有以下代码:

const init = async (): Promise<types.IContextObject> => {
  let context: types.IContextObject;
  try {
      context = await createContext(dataObj);
  } catch (e) {
      dataObj.errors.insert({ message: e.message });
      process.exit(1);
  }

  context.info.insert({
    message: `Using Rules: `.bold + `${Object.keys(context.rules).join(', ')}`
  });
  return context;

};

在此我得到以下编译器错误:

Variable 'context' is used before being assigned.
let context: types.IContextObject

如果我在 try 块中移动最后两行,我会得到:

Function lacks ending return statement and return type does not include 'undefined'.

【问题讨论】:

    标签: typescript asynchronous async-await


    【解决方案1】:

    您的变量 context 在 try 块之外未定义。将您的插入并返回到 try 块内并在您的 catch 中返回 null,或者在声明时将 context 设置为 null;但是,如果您在 catch 语句之后没有适当的 null 检查就执行后者,则在尝试访问 info 时可能会引发错误。

    【讨论】:

      【解决方案2】:

      如果你把它放在 try 之外,就不能保证 value 存在。如果放在try里面,就得提供第二个return方法,这样在try失败的时候就可以返回一些东西。

      因此,要么为context 提供默认值,要么在底部提供默认返回语句。这些都可以正常工作。

      【讨论】:

        猜你喜欢
        • 2020-08-26
        • 1970-01-01
        • 2014-11-01
        • 2020-11-19
        • 2016-12-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多