Getting errors in typescript

Asked
Active3 hr before
Viewed126 times

12 Answers

errorstypescriptgetting
90%

Creates an instance representing an error that occurs when a numeric variable or parameter is outside of its valid range.,Creates an instance representing an error that occurs when de-referencing an invalid reference. e.g.,Creates an instance representing an error that occurs when a variable or parameter is not of a valid type.

try {
   throw new Error('Something bad happened');
} catch (e) {
   console.log(e);
}
load more v
88%

Whenever TypeScript finds an error, it tries to explain what went wrong in as much detail as possible. Because its type system is structural, this often means providing somewhat lengthy descriptions of where it found a problem.,TypeScript found an error when checking the last line. Its logic for issuing an error follows from its logic for determining if the assignment is OK:,Explore how TypeScript extends JavaScript to add more safety and tooling.

Here’s an example that produces an error message longer than the example itself:

tslet a: {
   m: number[]
};
let b = {
   m: [""]
};
a = b;
Type '{ m: string[]; }'
is not assignable to type '{ m: number[]; }'.
Types of property 'm'
are incompatible.
Type 'string[]'
is not assignable to type 'number[]'.
Type 'string'
is not assignable to type 'number'
.2322 Type '{ m: string[]; }'
is not assignable to type '{ m: number[]; }'.
Types of property 'm'
are incompatible.
Type 'string[]'
is not assignable to type 'number[]'.
Type 'string'
is not assignable to type 'number'.
load more v
72%

 Pretag team - issue, fix, solve, resolve
65%

Using new.target has the advantage that you don't have to hardcode the prototype, like some other answers here proposed. That again has the advantage that classes inheriting from CustomError will automatically also get the correct prototype chain. ,As a recommendation, you can manually adjust the prototype immediately after any super(...) calls.,However, any subclass of FooError will have to manually set the prototype as well. For runtimes that don't support Object.setPrototypeOf, you may instead be able to use __proto__.

As a recommendation, you can manually adjust the prototype immediately after any super(...) calls.

class FooError extends Error {
   constructor(m: string) {
      super(m);

      // Set the prototype explicitly.
      Object.setPrototypeOf(this, FooError.prototype);
   }

   sayHello() {
      return "hello " + this.message;
   }
}
load more v
75%

You just need to help it out with a bit of type information:

interface IExample {
   content: string;
   opened ? : bool;
   value ? : string;
   children ? : IExample[];
}

var testHier: IExample[] = [{
      content: "1",
      opened: true,
      children: [{
         content: "1.1"
      }]
   },
   {
      content: "2",
      opened: true,
      children: [{
            content: "2.1",
            opened: false,
            children: [{
               content: "2.1.1",
               value: "2.1.1"
            }]
         },
         {
            content: "2.2",
            value: "2.2"
         }
      ]
   }
];
load more v
40%

Correctly handling and throwing errors in Javascript, or Typescript in our case, is always a painful experience and a journey with many places to get it wrong.,Since throwing error does not reflect on the method’s signature, all the safety of typed languages such as Typescript becomes useless since you are neither forced nor hinted, as a caller of such method, to do something with that error.,The expected errors are the ones you really want to avoid throwing and that should appear in the method’s signature.

/n

We might want to affect the method signature to force the caller to handle that At least one patient count was negative case according to its context.

At least one patient count was negative
load more v
22%

Because neither the compiler nor the types tell you that makeHttpRequest can fail (read: throw), you will eventually get a runtime error. This is a waste of time, money and happiness for everyone. People begin to ask why they're using TypeScript if the compiler isn't helping them with something so basic as adding a try / catch block.,Users of your API are not required to catch (the compiler doesn't enforce it). This means you will eventually hit a runtime error ... it's just a matter of time,Users of your API are not required to catch (the compiler doesn't enforce it). This means you will eventually hit a runtime error ... it's just a matter of time

type ResponseData = {
  statusCode: number
  responseBody?: ResponseBody
}

const makeHttpRequest = async (url: string): Promise<ResponseData> => {
  if (!isUrl(url)) {
    throw new Error(
      'Invalid string passed into `makeHttpRequest`. Expected a valid URL.'
    )
  }

  // ...
  // other business logic here
  // ...

  return { ... } // ResponseData
}
load more v
60%

Using the example function from point 1: ,Sometimes things fail — that's a fact of life and programming. So as a programmer, you're going to have to write error-handling code. Thankfully TypeScript has some handy features which can help us to create simple and maintainable error-handling code.,You’ll likely have operations that can fail in many exciting ways, which can also be encoded in these types. For example, by a discriminated union:

// No information in the type that this is an error,
// you would have to inspect the value to check
let firstError: string = "Something terrible occurred";

interface TerribleError {
   code: "TERRIBLE_ERROR";
   message: string;
}

// It is clearly indicated in the type that this is an error,
// the exact value of the variable is less important
let secondError: TerribleError = {
   code: "TERRIBLE_ERROR",
   message: "Something terrible occurred",
};
load more v
48%

In this article I will explain what is try catch statement and how to delete element from array in TypeScript with an example. ,for exception handling;  ,catch statement in typescript

 Pretag team - issue, fix, solve, resolve
23%

In this article, you will learn about handling errors in TypeScript.,    // define various operations in case if BadRequestError occured  ,        // define various operations in case if NotFoundError occured  

 Pretag team - issue, fix, solve, resolve
90%

Error objects are thrown when runtime errors occur. The Error object can also be used as a base object for user-defined exceptions. See below for standard built-in error types.,Runtime errors result in new Error objects being created and thrown.,Creates a new Error object.

try {
   throw new Error('Whoops!')
} catch (e) {
   console.error(e.name + ': ' + e.message)
}
load more v
88%

Which brings me to the focus of this article—how we can work with TypeScript to handle errors.,Over the past year I've been working on a large TypeScript project, and I'm happy to say I'm now officially on "team TypeScript".,Previously I've felt a little cautious about jumping on the TypeScript hype train for two main reasons:

function throwsError() {
   throw new Error('😱')
}

try {
   throwError()
} catch (error) {
   // we have access to the error here.
}
load more v

Other "errors-typescript" queries related to "Getting errors in typescript"