node.js - '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() });
}
}
);
关于我能做些什么的任何想法?
解决方案
正如我在另一个答案中所解释的那样,您从中获得的值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
使其成为这三个特定字符串文字之一。
推荐阅读
- rust - 铸造钢筋混凝土
到 Rc - python-3.x - 带有 CLI 实用程序的私有仓库中的 Python 包 - 如何部署、使用和构建
- javascript - 输入中的特殊字符以 %nn 形式出现
- javascript - 无法理解 Redux-Saga 中的非阻塞调用
- algorithm - 合并排序算法合并功能不起作用
- vue.js - Axios PUT 对 DRF Api 的请求通过,但未更新
- aws-cdk - 如何在 aws cdk 中使用自定义资源将文件上传到 s3 存储桶
- highcharts - Highcharts 8 - 在窗口调整大小时更改图表类型
- flutter - 如何确定 Flutter Web 应用是在手机还是 PC 上运行?
- algorithm - 如何正确编号两个字母字符?