{

How to declare a function throws an error in TypeScript


In Programming, Error is a common requirement to handle inside a code.

Handling error is a programmer’s responsibility to have clean code and avoid the graceful exit of an application.

The typescript compiler catches the compile-time errors with type safety.

How can you handle runtime errors in typescript.?

It provides an Error object to indicate that an error occurred.

In Typescript, the Error object is a Runtime exception or error. Currently, Typescript supports never type which supports any type of data.

In Typescript error handling using try and catch

try {
  throw new Error("error is thrown");
}
catch (e){
  console.log((e.message);
}

How do you declare a function which throws Error?

Unlike other programming languages as seen below, This is not supported to function throwing an error. With current version typescript(4.3.x), it is not valid

function myfunction(param:string): throws Error{

}

You can write as using never and union operator

function myfunction(test: string): string | never {
    if(!test){
        throw new Error();
    }
    return string;
}

The above function possibility of throwing an error as well as a string.

You can combine the never type with boolean or number using the union pipe operator.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.