Home > Blockchain >  in Typescript, try...catch error object shows "Object is of type 'unknown'.ts(2571)&q
in Typescript, try...catch error object shows "Object is of type 'unknown'.ts(2571)&q

Time:10-03

router.get('/cells', async (req, res) => {
    try {
      const result = await fs.readFile(fullPath, { encoding: 'utf-8' });
      res.send(JSON.parse(result));
    } catch (err) {
      if (err.code === 'ENOENT') { // Object is of type 'unknown'.ts(2571) (local var) err: unknown
        await fs.writeFile(fullPath, '[]', 'utf-8');
        res.send([]);
      } else {
        throw err;
      }
    }

err.code make this ts error : Object is of type 'unknown'.ts(2571)

I definitely know that err.code exists, so I want to know how to define the type(or interface) of err?

(tsc version info : My global typescript version is v4.3.5 and the above code belongs to my project which has typescript v4.1.2)

CodePudding user response:

In JavaScript/TypeScript you can throw anything, not only errors. In theory it could be anything in the catch block. If you want to prevent the type error it could make sense to check if the unknown value is a system error before checking the code.

if (err instanceof SystemError && err.code === 'ENOENT') {
  // file not found
}

CodePudding user response:

Just very recently, Typescript has been update to make error object inside catch be unknown instead of any

which means, your code looks something like this to your compiler

catch(e: unknown) {
// your logic
}

Provide your own interface to avoid this error:

catch(e : unknown) {
e = e as YourType
// your logic
}

You can still use any there, but it's not recommended.

  • Related