Open In App

How to Declare a Function that Throws an Error in TypeScript ?

Last Updated : 20 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to declare the functions that throw errors in TypeScript. A function can throw an error if the logic is not correct or you can deliberately declare the function that always throws an error. A function can be created with the different return types with the required type of value it returns.

We will create the error functions with two types of return values as discussed below:

Declare using the void type return value

A function whose return type is not defined will automatically return a void type value. This type of function will throw an error if they accidentally return something.

Syntax:

function function_name(): void/empty{}

Example: The below example will show how you can create a function that throws an error with a void type return value.

Javascript




function myFunc1() {
    throw new Error(`This is a function
                      that throws error`);
}
 
function myFunc2(): void {
    return `It will throw error as
              functions with void return
              type can not return anything`;
}
 
myFunc1();
myFunc2();


Output:

This is a function that throws error
Type 'string' is not assignable to type 'void'

Declare using the never type return value

The function with never type return value will never return anything after the function execution.

Syntax:

function function_name(): never {}

Example: The below example will illustrate how to declare error functions with never type return value.

Javascript




function myFunc1(): never {
    throw new Error(`This is a function
                     with never type return
                     value that throws error`);
}
 
function myFunc2(myVal: number): number | never {
    if (myVal < 20) {
        return myVal;
    }
    else {
        throw new Error("Passed value is greater than 20");
    }
}
 
console.log(myFunc2(18));
myFunc2(100);
myFunc1();


Output:

18
Passed value is greater than 20
This is a function with never type return value that throws error


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads