如何在 Typescript 中使用 Try and Catch

How to use Try and Catch with Typescript

我想当函数 sum 的两个参数是数字时,代码成功,但是当两个参数之一不是数字时我想抛出异常。

  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');
  }

现在作为测试,我用字符串值代替 num2,但代码 运行 没有在控制台中显示异常 我的意思是它没有从 catch 块

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

当参数不是数字时,我想在控制台中记录它,如何实现?

刚刚抛出一个新错误:

  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);
  }

Typescript 不会在运行时抛出异常,它会编译成原生 javascript。它只能显示你的类型错误并在编译期间抛出错误。 如果你想捕获异常,你可以使用 throw new Error('/*error text*/')