如何声明一个在 Typescript 中引发错误的函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49434751/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:17:41  来源:igfitidea点击:

How to declare a function that throws an error in Typescript

typescript

提问by The224

In Java I would declare a function like this:

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

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.

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

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 中做同样的事情?编译器会告诉我,如果没有 try/catch,我将无法使用该函数。

回答by Estus Flask

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).

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

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:

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

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, neveris absorbed by return type.

当函数有可能返回一个值时,never被返回类型吸收。

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

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) => booleanby typing system.

它可以提示开发人员可能出现未处理的错误(以防函数体不清楚),但这不会影响类型检查,也不能强制try..catch;该函数的类型(test: boolean) => boolean由类型系统考虑。

回答by sompnd

It is not possible at this moment. You can check out this requested feature: https://github.com/microsoft/TypeScript/issues/13219

目前是不可能的。您可以查看此请求的功能:https: //github.com/microsoft/TypeScript/issues/13219

回答by Flavien Volken

You cannot using pure ts (v<3.9) I hope it will be available in the future. A workaround is however possible, it consists of hiding the possible thrown types in the method's signature to then recover those types in the catch block. I made a package with this workaround here: https://www.npmjs.com/package/ts-throwable/v/latest

您不能使用纯 ts (v<3.9) 我希望将来可以使用它。然而,一种解决方法是可能的,它包括在方法的签名中隐藏可能抛出的类型,然后在 catch 块中恢复这些类型。我在这里用这个解决方法做了一个包:https: //www.npmjs.com/package/ts-throwable/v/latest

usage is more or less as follow:

用法或多或少如下:

import { throwable, getTypedError } from 'ts-throwable';
class CustomError extends Error { /*...*/ }

function brokenMethod(): number & throwable<CustomError> {
    return Math.random() < 0.5 ? 42 : throw new CustomError("Boom!");
}

try {
    const answer: number = brokenMethod()
}
catch(error){
    // `typedError` is now an alias of `error` and typed as `CustomError` 
    const typedError = getTypedError(error, brokenMethod);
}