Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

210
Views
How to get the `code` property of an error in a `try/catch` using TypeScript 4.4?

I'm trying to get to the code property of an error caught by try/catch like so:

  try {
    const { foo } = await import('./foo');
    // [...]
  } catch (error) {
    if (error instanceof Error) {
      if (error.code === 'MODULE_NOT_FOUND') {
         // [...]
      }
    }
  }

but this gives me the following compilation error:

TSError: ⨯ Unable to compile TypeScript:
src/server.ts:44:17 - error TS2339: Property 'code' does not exist on type 'Error'.

I installed @types/node@16.x.x and my tsconfig.json looks like:

{
  "extends": "@tsconfig/node16/tsconfig.json",
  "include": ["src/**/*"],
  "exclude": ["node_modules", "**/*.spec.ts"]
}

but I noticed that Visual Studio Code gets the definition for the Error class from:

C:\Users\kg\AppData\Local\Programs\Microsoft VS Code\resources\app\extensions\node_modules\typescript\lib\lib.es5.d.ts

How do I make TypeScript see that there's a code property in Error without having to define my own type or interface?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!