Open In App

TypeScript Assertion functions

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:

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.




// Define an assertion function
// which is named as assertFnArray
function asssertFnArray(value: unknown):
    asserts value is number[] {
 
    // Checking if the 'value' is not an
    // array or if it has non-number items
    if (!Array.isArray(value) ||
        value.some((item) => typeof item !== 'number')) {
        throw new Error("Assertion failed");
    }
}
// Creating a unknown varibale named arr
// arr has the array of numbers from 1-4
const arr: unknown = [1, 2, 3, 4];
 
// Applying the assertion function to 'arr'
asssertFnArray(arr);
 
// Now TypeScript knows that
// 'arr' is of type number[]
// Performing an operation on
// 'arr' (calculating the sum of its elements)
console.log(arr.reduce((acc, curr) => acc + curr, 0));

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.




// Defining a custom type 'Person' with 'name'
// as a string and 'age' as a number
type Person = { name: string; age: number };
 
// Creating an assertion function named 'assertPerson'
// to make sure an object follows to the 'Person' type
function assertPerson(value: unknown): asserts value is Person {
    // Checking if 'value' is an object,
    // not null or undefined, and its 'name'
    // is a string and 'age' is a number
    if (
        typeof value !== 'object' ||
        !value ||
        typeof (value as Person).name !== 'string' ||
        typeof (value as Person).age !== 'number'
    ) {
        throw new Error("Assertion failed");
    }
}
 
// Creating an unknown variable 'obj'
// with an object that represents a Geek Data
const obj: unknown = { name: "Geek1", age: 23 };
 
// Applying the assertion function 'assertPerson' to 'obj'
assertPerson(obj);
 
// TypeScript knows that 'obj' is of type 'Person'
// Printing the output
console.log(`Name: ${obj.name}, Age: ${obj.age}`);

Output:

"Name: Geek1, Age: 23" 

Article Tags :