在 TypeScript 中声明一个抛出错误的函数
Declare a function that throws an Error in TypeScript
要声明抛出错误的函数,请将其返回类型设置为never
. 该never
类型用于从不返回值的函数,换句话说,就是抛出异常或终止程序执行的函数。
// 👇️ function throwErr(): never function throwErr(): never { throw new Error('Something went wrong'); }
never
类型在 TypeScript 中很少使用。
当函数永远不会到达返回语句时使用它,这主要有两个原因:
- 函数抛出错误
- 函数无限循环
如果我们没有显式键入函数的返回值,TypeScript 会将其推断为void
.
// 👇️ function throwErr(): void function throwErr() { throw new Error('Something went wrong'); }
never
和
void之间的区别在于它void
用于不返回任何内容(或 return
undefined
)的函数。
如果我们不小心从一个返回类型为 的函数返回一个值
void
,我们就会得到一个错误。
never
永远不会返回任何东西。很少需要将函数的返回类型设置为never
. 例如,如果函数仅在某些时候抛出错误,则不应将其返回类型设置为never
.
function sometimesThrow(): number { if (Math.random() > 0.5) { return 100; } throw new Error('Something went wrong'); } // 👇️ const result: number const result = sometimesThrow(); console.log(result.toFixed());
The function in the example above returns a number
some of the time, and
throws an error on some invocations.
You could use a
union type
to set its value to number
or never
.
function sometimesThrow(): number | never { if (Math.random() > 0.5) { return 100; } throw new Error('Something went wrong'); } // 👇️ const result: number const result = sometimesThrow(); console.log(result.toFixed());
But this is only useful to inform your colleagues that the function might throw
an error.
result
variable is still typed as a number
even though we set the function’s return type to number | never
.This is because every other type absorbs never
in a union type.
// 👇️ type T = number type T = number | never;
Notice that number | never
is simplified to number
. This is the case when
using never
with any other type in a union.
number | never
, because that would indicate to your colleagues that the function might throw an unhandled error and they might have to wrap the invocation in a try/catch
statement.However, this doesn’t technically influence the function’s return type.
It should also be noted that there isn’t a way for you to distinguish the type
of error a function throws.
For example, if you have a class CustomError
that extends from Error
,
there’s no way for you to tell TypeScript that your function throws a
CustomError
instead of an Error
.
If you set the function’s return type to CustomError
, this means that the
function will return (and not throw) a value typed as CustomError
.