Open In App

TypeScript Assertion functions

Last Updated : 07 Nov, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

TypeScript Assertion functions are nothing but the functions that allow us to mainly create the custom type guards that assert the type of a value on our specific criteria. The most suitable use of Assertion Functions is when we are working with the more complex data structures.

Syntax:

function assert(condition: any, msg?: string):  asserts condition {
if (!condition) {
throw new AssertionError(msg);
}
}

Parameters:

  • assert: This is the name of the function.
  • condition: any, msg?: string: Thi is the condition which will be checked and the message of string type is optional.
  • throw new AssertionError(msg): This will throw the error if the condition gets unsatisfied.

Example: In this example, we are defining a function in which we are asserting the value, if the value is other than number it will throw the error else it will give the sum of the values passed in the function.

Output:

10

Example:In this example, we are checking whether the passing object has the defined type of properties or not. If it has other type other that the given type in the function then it will throw the error.

Output:

"Name: Geek1, Age: 23" 

Next Article

Similar Reads