Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • TypeScript Tutorial
  • TS Exercise
  • TS Interview Questions
  • TS Cheat Sheet
  • TS Array
  • TS String
  • TS Object
  • TS Operators
  • TS Projects
  • TS Union Types
  • TS Function
  • TS Class
  • TS Generic
Open In App
Next Article:
TypeScript Assertion functions
Next article icon

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.

JavaScript
// 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.

JavaScript
// 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" 

Next Article
TypeScript Assertion functions

G

gauravggeeksforgeeks
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • Geeks Premier League
  • TypeScript
  • Geeks Premier League 2023

Similar Reads

    TypeScript Assertions Type
    TypeScript Assertions Type, also known as Type Assertion, is a feature that lets developers manually override the inferred or expected type of a value, providing more control over type checking in situations where TypeScript's automatic type inference may not be sufficient.Syntaxlet variableName: As
    2 min read
    TypeScript Function Type Expressions
    In this article, we are going to learn about TypeScript Function Type Expressions in Typescript. TypeScript is a popular programming language used for building scalable and robust applications. In TypeScript, a function type expression represents the type of a function, including its parameter types
    3 min read
    Explain Type assertions in TypeScript
    In TypeScript, type assertions allow developers to override the compiler's inferred type, informing it of the specific type of a value. Type assertions are purely compile-time constructs and do not alter the runtime behavior of the code. They are particularly useful when interfacing with APIs or thi
    3 min read
    PHPUnit assertIsNotInt() Function
    The assertIsNotInt() function is a builtin function in PHPUnit and is used to assert whether the given actual variable is not an integer. This assertion will return true in the case if the actual variable is doesn't integer else returns false. In case of true the asserted test case got passed else t
    2 min read
    PHPUnit assertIsInt() Function
    The assertIsInt() function is a builtin function in PHPUnit and is used to assert whether the given actual variable is an integer or not. This assertion will return true in the case if the actual variable is an integer else returns false. In case of true the asserted test case got passed else test c
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences