user16350114
user16350114

Reputation:

How to use Try and Catch with Typescript

I want when the two arguments of function sum are numbers, the code success, but when one of the two arguments is not a number I want to throw an exception.

  const sum = (num1: number, num2: number) => {
    return num1 + num2;
  };

  try {
    typeof sum(8, 'A') === 'number';
  } catch (e) {
    console.log('the type you entered is NaN');
  }

Now as a Test I put a string value instead num2 but the code ran without showing the exception in the console I mean it didn't log that 'the type you entered is NaN' from the catch block

catch (e) {
    console.log('the type you entered is NaN');
  }

I want to log that in console when arguments are not numbers, How to make that?

Upvotes: 1

Views: 5340

Answers (2)

ZloiGoroh
ZloiGoroh

Reputation: 443

Typescript would not throw exceptions in runtime, it compiles into native javascript. It can only show your mistakes with types and throw errors during compilation. If you want to catch an exception you can use throw new Error('/*error text*/')

Upvotes: 1

Francesco Clementi
Francesco Clementi

Reputation: 2102

Just throw a new error:

  const sum = (num1: number, num2: number) => {
    return num1 + num2;
  };

  try {
    if (typeof sum(8, 'A') !== 'number'){
      throw new Error('the type you entered is NaN')
    }
  } catch (e) {
    console.log(e);
  }

Upvotes: 0

Related Questions