Categories
TypeScript Answers

How to declare a function that throws an error in TypeScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *