简体   繁体   中英

How to fix @ts-expect-error ts-migrate(2571) on Typescript when convert js to ts

I begin to start with typescript and I was trying to convert my JS file to TS.

I have a class with the function below

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

I dont know how to identify which is the object type of "all_ocorrencies" in

let all_ocorrencies = await mongoDatabaseStockOperations.findAllOcorrencesOrderByValue(Constants.STOCKS_REPORT_COLLECTION)

The function findAllOcorrencesOrderByValue return a Promise with objects from a mongodb database, but I don't how which is the type of that object.

How can I fix that?

unknown type

Error 2571 refers to the skipping of type-checking on type unknown . Doing a type check will affirm a specific type.

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.

To certify that x is a specific type, we can pass it into an if statement

if (typeof x === 'string') x.toString(); // Inline if
if (typeof x === 'number') { // Multiline if
    x += 2;
}

It is often encourage to make sure that intellisense or your code editor's/IDE's autocomplete predicts methods and more information corresponding to the type.

Notice how any variable with an unknown type, no autocomplete is filled, where as when manually type-checked, it has all the autocomplete to the related type.

Implementation

Where as the specific object that has the type unknown, I'm not sure of which, but the code should look something like this:

if (typeof x !== 'object') return;

In the case of 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")    
});

In the case of 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")    
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM