[英]How to fix @ts-expect-error ts-migrate(2571) on Typescript when convert js to ts
我開始從打字稿開始,我試圖將我的 JS 文件轉換為 TS。
我有一個具有以下功能的課程
應用程序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,但我不知道該對象的類型是什么。
我該如何解決?
unknown
類型錯誤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;
}
通常鼓勵確保智能感知或您的代碼編輯器/IDE 的自動完成功能預測與類型相對應的方法和更多信息。
請注意任何具有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")
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.