Is there a way to accurately identify the type of error that arises from a promise?

Utilizing the promise method within my script is essential.

  try {
    const secretData = await secretManager.getSecretValue({ SecretId: secretId }).promise();
    const secretString = secretData.SecretString;
  } catch (error) {
    if (error.code !== 'ResourceNotFoundException') {
      throw(error);
    }
  }

Upon inspecting the promise method, it reveals a type of

Promise<PromiseResult<AWS.SecretsManager.GetSecretValueResponse, AWS.AWSError>>
.

However, the type of the error in the catch block remains as unknown.

I am eager to understand how I can prompt TypeScript to recognize the error's type.

Answer №1

Issue

In TypeScript, the exception variable in a catch block is typed as unknown for safety reasons since the type of the thrown error is not known due to the possibility of throwing any valid JavaScript expression. However, there have been ongoing discussions about enhancing this behavior, refer to TypeScript#13219 for more information.

Resolution

To address this, you can assist TypeScript in narrowing down the error type using the following methods:

Narrowing with instanceof

If you know the specific error class, you can narrow down the error by checking if it is an instance of that class.

class CustomError extends Error {
  foo: string;

  constructor(message: string) {
    super(message);
    this.name = "CustomError";
    this.foo = "foo";
  }
}

function foo() {}

try {
  foo();
} catch (error) {
  if (error instanceof CustomError)  {
    console.log(error);
    //          ^^^^^
    //        Hover here
    // `var error: CustomError` should appear
    // `error` has been narrowed to `CustomError`
  }
}

TypeScript Playground

Type predicate and in operator narrowing

You can also narrow down the error type by checking for specific properties that your error should possess through a type predicate.

class CustomError extends Error {
  foo: string;

  constructor(message: string) {
    super(message);
    this.name = "CustomError";
    this.foo = "foo";
  }
}

function foo() {}

function isCustomError(error: any): error is CustomError {
  return "foo" in error;
}

try {
  foo();
} catch (error) {
  if (isCustomError(error)) {
    console.log(error);
    //          ^^^^^
    //        Hover here
    // `var error: CustomError` should appear
    // `error` has been narrowed to `CustomError`
  }
}

TypeScript Playground

For additional information

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing Angular 2's NgFor directive in SVG Elements

I want to use ngFor to draw an SVG Element that consists of lines. I am struggling with the implementation and need some help fixing the code. Here is what I have so far: my-component.js: import {Component} from 'angular2/core'; @Component({ ...

Angular2 restricts Http requests within a specified time interval

I am a beginner with angular 2 and I have a value that is linked to user interaction that needs to be sent over http requests. The value can change multiple times per second, so I want to limit the http requests to one every 2 seconds during user interacti ...

Can you explain the distinction between App: React.FunctionComponent and App = (): React.FunctionComponent()?

Currently exploring the depths of typescript. Can someone clarify the distinction between these two code snippets: const App: React.FunctionComponent<CustomProps> = (props: CustomProps) => { return <div>Hello World!</div>; }; and: ...

Guide for setting CSRF cookie in Next.js for Django

Just dipping my toes into the world of Nextjs while tinkering with a frontend interface for my trusty Django app Let's take a peek at my route.js file where the magic happens, as it makes a call to the django endpoint import { NextResponse } from &a ...

Issue: Control with the specified name '0' could not be located

Kindly review this code snippet and assist me in resolving the issue. I have set up a formArray where the label and formControlName do not match, so I have utilized mapping to synchronize them. Upon receiving a response from the API, I initialize the for ...

One-of-a-kind npm module for typescript

As part of my project, I am enhancing an existing library to make it compatible with TypeScript. To showcase this modification, I have condensed it into a succinct Minimal working example The specified requirements To ensure backward compatibility, the li ...

What is a way to merge all the letters from every console.log result together?

I'm encountering an issue - I've been attempting to retrieve a string that provides a link to the current user's profile picture. However, when I use console.log(), the output appears as follows: Console Output: https://i.sstatic.net/70W6Q ...

An issue occurred while attempting to pretty-print JSON in Typescript

Currently, I am attempting to utilize https://www.npmjs.com/package/prettyjson in conjunction with Typescript; however, it is unable to locate the module. To begin, I created a package.json file: { "name": "prettyjson-test", "description": "prettyjso ...

Limiting the combinations of types in TypeScript

I have a dilemma: type TypeLetter = "TypeA" | "TypeB" type TypeNumber = "Type1" | "Type2" I am trying to restrict the combinations of values from these types. Only "TypeA" and "Type1" can be paired together, and only "TypeB" and "Type2" can be paired tog ...

When using react-admin with TypeScript, it is not possible to treat a namespace as a type

Encountering issues while adding files from the react-admin example demo, facing some errors: 'Cannot use namespace 'FilterProps' as a type.' Snippet of code: https://github.com/marmelab/react-admin/blob/master/examples/demo/src/orde ...

Typedoc encountering an issue due to the require syntax

I am currently attempting to create documentation using typedoc. The lines in my typescript file are as follows: var validator: any = require('validator'); import * as _ from 'lodash'; var mqtt: any = require('mqtt'); var fs ...

Azure pipeline failing to run Visual Studio 2017 task because of outdated Typescript SDK version

The Visual Studio 2017 build encounters an error during the build process src\Service\node_modules\utility-types\dist\aliases-and-guards.d.ts(10,51): Error TS2304: Build:Cannot find name 'bigint This issue is specific to the ...

Determining the height of dynamically rendered child elements in a React application

Looking for a way to dynamically adjust the heights of elements based on other element heights? Struggling with getting references to the "source" objects without ending up in an infinite loop? Here's what I've attempted so far. TimelineData cons ...

What is the best way to implement generics for a zip function in TypeScript?

I want to enhance this JS function by including types: function zip(array1, array2) { const length = Math.min(array1.length, array2.length); const result = []; for (let i = 0; i < length; i++) { result.push([array1[i], array2[i]]); } retur ...

Alert: Circular dependency identified: Unable to determine the module

During the development of our project, we encountered an issue: fail: Microsoft.AspNetCore.SpaServices[0] WARNING in Circular dependency detected: fail: Microsoft.AspNetCore.SpaServices[0] src\app\app.module.ts -> src\m ...

Ways to manage an interactive pricing structure chart in Angular?

In my application, users can choose from four different types of plans that are retrieved from the backend. Once a plan is selected, they are directed to a payment page. The pricing table page can be revisited, and if a user has already purchased a plan, t ...

The type 'MutableRefObject<undefined>' cannot be assigned to the type 'LegacyRef<HTMLDivElement> | undefined'

I have created a customized hook that takes a ref object and observes its behavior: import { useState, useEffect, MutableRefObject } from "react"; const UseOnScreen = (ref: MutableRefObject<undefined>) => { const [isIntersecting, setI ...

This code cannot be called as a function, Every individual in the union

My approach has been aligned with the current architecture, focusing on reducing complexity as much as possible. I have strived for the best possible outcome, but encountered a single failed test along the way. After three days of struggling, I'm cl ...

Custom type declaration file in Typescript fails to function properly

I have searched through countless solutions to a similar issue, but none seem to work for me. I am attempting to utilize an npm package that lacks TypeScript type definitions, so I decided to create my own .d.ts file. However, every time I try, I encounter ...

Enhance your coding experience with TypeScript's autocomplete in Visual Studio Code

After migrating a project from JavaScript to TypeScript, I am not seeing autocomplete suggestions or type hints when hovering over variables in Visual Studio Code editor (Version 1.7.2). Even the basic example provided below does not display any auto-com ...