在 Java 中我会这样声明一个函数:
public boolean Test(boolean test) throws Exception {
if (test == true)
return false;
throw new Exception();
}
而且我可以在不处理异常的情况下使用这个函数。
如果可能的话,如何在 Typescript 中做同样的事情?编译器会告诉我,如果没有 try/catch,我无法使用该函数。
最佳答案
TypeScript 中没有这样的功能。仅当函数返回错误而不是抛出错误时才可以指定错误类型(这种情况很少发生并且很容易成为反模式)。
唯一相关的类型是 never
.它仅适用于函数肯定会抛出错误的情况,不能比这更具体。它和其他任何类型一样,只要不引起类型问题就不会引起类型错误:
function Test(): never => {
throw new Error();
}
Test(); // won't cause type error
let test: boolean = Test(); // will cause type error
当函数有可能返回值时,从不
被返回类型吸收。
可以在函数签名中指定,但仅供引用:
function Test(test: boolean): boolean | never {
if (test === true)
return false;
throw new Error();
}
它可以向开发人员提示可能存在未处理的错误(以防在函数体中不清楚),但这不会影响类型检查并且不能强制执行 try..catch
;通过键入 system,此函数的类型被视为 (test: boolean) => boolean
。
关于typescript - 如何声明一个在 Typescript 中抛出错误的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49434751/