我开始使用typescript,并尝试将我的JS文件转换为TS。
我有一个包含以下函数的类
APP.JS
async function get_stocks_saved_on_database(request: any, response: any) {
let mongoDatabaseStockOperations = new MongoDatabaseStockOperations()
let all_ocorrencies = await mongoDatabaseStockOperations.findAllOcorrencesOrderByValue(Constants.STOCKS_REPORT_COLLECTION)
// @ts-expect-error ts-migrate(2571) FIXME: Object is of type 'unknown'.
all_ocorrencies.forEach((element: any) => {
response.write(element.stock_name + " | " + element.stock_value + " | " + element.percent_difference + " | " + element.day + "\n")
});
response.end()
}
async findAllOcorrencesOrderByValue(my_investments_collection: any){
console.log("start findAllOcorrences")
return new Promise(function(resolve, reject) {
// Do async job
MongoDb.MongoClient.connect(url, function(err, db) {
if (err) reject(err);
var dbo = db?.db(database_name);
var mysort:MongoDb.Sort = { "day": -1, "percent_difference": -1 };
dbo?.collection(my_investments_collection).find().sort(mysort).collation({locale: "en_US", numericOrdering: true}).toArray(function(err, result) {
if (err) reject(err);
console.log(result);
resolve(result)
db?.close();
});
});
});
}我不知道如何识别中"all_ocorrencies“的对象类型
let all_ocorrencies = await mongoDatabaseStockOperations.findAllOcorrencesOrderByValue(Constants.STOCKS_REPORT_COLLECTION)函数findAllOcorrencesOrderByValue使用mongodb数据库中的对象返回一个Promise,但我不知道哪个是该对象的类型。
我怎么才能修复它呢?
发布于 2021-11-04 17:22:04
unknown类型
Error 2571指的是跳过对类型unknown的类型检查。执行类型检查将确认特定的类型。
let x: unknown;
x.toString(); // Expected output: Error: Object is of type 'unknown'.
x + 1; // Expected output: Error: Object is of type 'unknown'.
Array[x] // Expected output: Error: Type 'unknown' cannot be used as an index type.为了证明x是一个特定的类型,我们可以将其传递到if语句中
if (typeof x === 'string') x.toString(); // Inline if
if (typeof x === 'number') { // Multiline if
x += 2;
}通常鼓励确保intellisense或代码编辑器/IDE自动完成功能预测与类型相对应的方法和更多信息。
注意任何类型为unknown的变量是如何填充的,没有自动完成,当手动检查类型时,它具有相关类型的所有自动完成。
实现
其中,作为具有unknown类型的特定对象,我不确定是哪一个,但代码应该如下所示:
if (typeof x !== 'object') return;在all_ocorrencies的情况下
if (typeof all_ocorrencies !== 'array') return; // Or handle it yourself
all_ocorrencies.forEach((element: any) => {
response.write(element.stock_name + " | " + element.stock_value + " | " + element.percent_difference + " | " + element.day + "\n")
});在element的情况下
all_ocorrencies.forEach((element: unknown) => {
if (typeof element !== 'object') return; // Or handle it yourself
response.write(element.stock_name + " | " + element.stock_value + " | " + element.percent_difference + " | " + element.day + "\n")
});https://stackoverflow.com/questions/69840167
复制相似问题