如何声明一个在 Typescript 中引发错误的函数 [英] How to declare a function that throws an error in Typescript

查看:26
本文介绍了如何声明一个在 Typescript 中引发错误的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java 中,我会声明一个这样的函数:

In Java I would declare a function like this:

public boolean Test(boolean test) throws Exception {
  if (test == true)
    return false;
  throw new Exception();
}

而且我可以在不处理异常的情况下使用这个函数.

And I can use this function without handling the exception.

如果可能,如何在 Typescript 中做同样的事情?编译器会告诉我,如果没有 try/catch,我将无法使用该函数.

If it is possible, how to do the same in Typescript? The compiler will tell me that I can't use the function without a try/catch.

推荐答案

TypeScript 中没有这样的功能.仅当函数返回错误而不是抛出错误时才可以指定错误类型(这种情况很少发生并且容易成为反模式).

There is no such feature in TypeScript. It's possible to specify error type only if a function returns an error, not throws it (this rarely happens and is prone to be antipattern).

唯一相关的类型是never.仅当函数肯定会抛出错误时才适用,它不能比这更具体.它和其他类型一样,只要不引起类型问题就不会引起类型错误:

The only relevant type is never. It is applicable only if a function definitely throws an error, it cannot be more specific than that. It's a type as any other, it won't cause type error as long as it doesn't cause type problems:

function Test(): never => {
  throw new Error();
}

Test(); // won't cause type error
let test: boolean = Test(); // will cause type error

当函数有可能返回一个值时,从不被返回类型吸收.

When there is a possibility for a function to return a value, never is absorbed by return type.

可以在函数签名中指定,但仅供参考:

It's possible to specify it in function signature, but for reference only:

function Test(test: boolean): boolean | never {
  if (test === true)
    return false;

  throw new Error();
}

它可以提示开发人员可能出现未处理的错误(以防函数体不清楚),但这不会影响类型检查,也不能强制 try..catch;这个函数的类型被认为是 (test: boolean) =>布尔值通过输入系统.

It can give a hint to a developer that unhandled error is possible (in case when this is unclear from function body), but this doesn't affect type checks and cannot force try..catch; the type of this function is considered (test: boolean) => boolean by typing system.

这篇关于如何声明一个在 Typescript 中引发错误的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆