'string | 类型的参数字符串[] |解析Qs | ParsedQs[]' 不能分配给类型为 'string' 的参数

时间:2021-01-14 21:47:00

标签: node.js string typescript firebase

在错误处理方面相当新手。

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

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

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

对此我能做些什么有什么想法吗?

1 个答案:

答案 0 :(得分: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 已知为这三个特定字符串文字之一。