Sometimes, we want to declare a function that throws an error in TypeScript.
In this article, we’ll look at how to declare a function that throws an error in TypeScript.
How to declare a function that throws an error in TypeScript?
To declare a function that throws an error in TypeScript, we can use never
as the return type.
For instance, we write
const test = (): never => {
throw new Error();
};
to create the test
function that throws an error.
We set its return type to the never
type so the TypeScript compiler will know that the function always throws an error.
Conclusion
To declare a function that throws an error in TypeScript, we can use never
as the return type.