首页 > 解决方案 > 'string | 类型的参数 字符串[] | 解析问题 | ParsedQs[]' 不可分配给“字符串”类型的参数

问题描述

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

我在此代码中收到 (Type 'undefined' is not assignable to type 'string') 错误

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

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

关于我能做些什么的任何想法?

标签: node.jsstringtypescriptfirebase

解决方案


正如我在另一个答案中所解释的那样,您从中获得的值request.query可能是一个复杂的对象,而不仅仅是一个string. 但是isValidType要求你通过 astring所以你会得到一个错误。

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

这里似乎没有必要,但您可以更改返回类型,使其isValidType成为类型保护

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

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


推荐阅读