【问题标题】:Variable is used before being assigned in typescript, when type provided提供类型时,在打字稿中分配之前使用变量
【发布时间】:2021-10-09 20:45:49
【问题描述】:

我在打字稿中有这段代码,但我不明白为什么它告诉我变量在分配之前已使用:

仅当我将类型添加到 database 变量时才会发生这种情况。这是一个基于 Vue/Quasar 的项目,使用 Typescript。请注意,如果我将类型指定为“任何”,那么我没有任何问题,但如果可以的话,我宁愿避免走这条路。

谁能建议我可能做错了什么以及可能的解决方案?

  import { SQLiteDBConnection } from '@capacitor-community/sqlite';

  let database: SQLiteDBConnection;
  try {
    database = await sqlite.retrieveConnection(this.connectionName);
  } catch (error) {
    // ignore
  }

  try {
    if (!database) {
      // workaround an issue if `retrieveConnection` fails
      await sqlite.closeConnection(this.connectionName);
    }
  } catch (error) {
    // ignore
  }

  try {
    if (!database) {
      database = await sqlite.createConnection(this.connectionName);
    }
  } catch (error) {
    // ignore
  }

  if (!database) {
    throw new Error('unable to create or retrieve connection');
  }

【问题讨论】:

    标签: typescript


    【解决方案1】:

    如果您这样初始化数据库变量:

      let database: SQLiteDBConnection | null = null;
    

    现在您的变量可以是 null 或数据库连接,并且它始终是已定义的,这似乎是您在文件中进一步假设的内容。

    【讨论】:

    • 或者只是let database: SQLiteDBConnection | undefined;,效果一样但不需要更改运行时代码
    猜你喜欢
    • 2021-06-22
    • 2020-05-22
    • 2018-05-06
    • 1970-01-01
    • 1970-01-01
    • 2018-04-29
    • 1970-01-01
    • 2020-07-16
    • 2021-07-23
    相关资源
    最近更新 更多