【问题标题】:Argument of type 'string | string[] | ParsedQs | ParsedQs[]' is not assignable to parameter of type 'string''string | 类型的参数字符串[] |解析问题 | ParsedQs[]' 不可分配给“字符串”类型的参数
【发布时间】:2021-04-19 23:11:43
【问题描述】:

在错误处理方面是个新手。

我在此代码中收到(类型“未定义”不可分配给类型“字符串”)错误

编辑:如果这有助于您理解问题,我决定添加整个代码页面。

type AuthClient = Compute | JWT | UserRefreshClient;

function isValidType(type: string): boolean {
  return (
    type === 'IMPORT_DATA' || type === 'EXPORT_MODEL' || type === 'TRAIN_MODEL'
  );
}

/**
 * A function to check & update progress of a long running progression
 * in AutoML.
 */
export const checkOperationProgress = functions.https.onRequest(
  async (request, response) => {
    const operationType = request.query['type'];
    if (!operationType) {
      response.status(404).json({ error: 'Operation `type` needed' });
      return;
    }
    if (!isValidType(operationType)) {
                         ^^^ ERROR ABOVE
      response.status(400).json({
        error: 'type should be one of IMPORT_DATA, EXPORT_MODEL, TRAIN_MODEL',
      });
      return;
    }
    try {
      const client = await auth.getClient({ scopes: [AUTOML_API_SCOPE] });

      const snapshot = await admin
        .firestore()
        .collection('operations')
        .where('type', '==', operationType)
        .where('done', '==', false)
        .get();

      if (snapshot.empty) {
        response.status(200).json({
          success: `No pending operations found for type ${operationType}`,
        });
        return;
      }

      // for each operation, check the status
      snapshot.docs.forEach(async doc => {
        await updateOperation(doc, client);
      });

      response.status(200).json({
        success: `${snapshot.docs.length} operations updated: ${operationType}`,
      });
    } catch (err) {
      response.status(500).json({ error: err.toJSON() });
    }
  }
);

知道我能做些什么吗?

【问题讨论】:

  • 从代码中,你分享我只能说dataset显然是一个字符串数组。因此,您可能应该将其减少为单个字符串。发送错误响应后,您也不会在第二个示例中返回。
  • 你的 isValidType 和 generateLabel 函数是什么样子的?
  • 嘿,抱歉。如果这有助于您理解问题,我已经添加了整个页面的代码。
  • 我不确定为什么会发生这种情况,我无法重现它。您应该通过返回if(!operationType) 案例来消除undefined 的可能性。
  • @LindaPaiste 我对如何实现这一点知之甚少,您能否详细说明我应该尝试做什么?

标签: node.js string typescript firebase


【解决方案1】:

正如my other answer 中所解释的,您从request.query 获得的值可能是一个复杂的对象,并不总是只是一个string。但是isValidType 要求你传递一个string 所以你会得到一个错误。

您的isValidType 函数正在检查type 和您的预定义字符串之间的严格相等性,因此我们可以将该函数更改为接受type: any,它不会对其行为产生任何影响。任何非字符串都保证返回 false。

这里似乎没有必要,但您可以更改返回类型,使 isValidType 变为 type guard

function isValidType(type: any): type is string { 
   ... 
}

它仍然返回一个boolean 值,但是当true 时,typescript 现在知道变量type 的类型为string。我们还可以定义返回类型,使得 type 被认为是这三个特定的字符串文字之一。

【讨论】:

    猜你喜欢
    • 2021-04-20
    • 1970-01-01
    • 2021-07-02
    • 2021-06-16
    • 2021-09-07
    • 1970-01-01
    • 2021-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多