Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • 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:
How to Check Types in Typescript?
Next article icon

How to enforce strict null checks in TypeScript ?

Last Updated : 23 Feb, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

In Typescript to enforce strict null checks in tsconfig.json file, we need to enable "strictNullChecks" to true. When "strictNullChecks" is false, the language generally ignores variables of type null and undefined. If null and undefined is used in places where a definite value is expected, it raises an error. When "strictNullChecks" is true when null and undefined is used a type error gets raised.

Example 1: Assigning null and undefined to string type variable

A null value is passed to a string-type variable.

JavaScript
let var1: string = null; 

Output:

When strict null checks are enabled.

If strict null checks are not enabled:

If undefined is given to a variable and strictnullchecks is true:

JavaScript
let var1: string = undefined; 

Output:

Example 2: Referencing variables before assigning values

When strictnullchecks are enabled variables that are not assigned any value cannot be referenced. The only exception is when the variable is of type "undefined", those variables can be referenced before being assigned by any value. 

JavaScript
let var1: string | number; let var2: string | null; let var3: string | undefined;  // Throws error var1;  // Throws error var2;  // Doesn't Throws error var3; var1 = 1; var2 = "abc";  // No error var1;  // No error var2; 

Output: This is how it looks like in code editor.

Example 3: Covering strictnullchecks

The below code is a small example of strictnullchecks. An interface is created and ?: is used while declaring variable age, it says the variable can be null or identified. As strict null checks are enabled when we try to display student.age it gives us warning. When it's further confirmed that student.age is not null no warning or error is given. 

JavaScript
interface Student {   name: string;   age?: number; }  function displayStudentInfo(student: Student) {    // Error TS2532: Object is possibly 'undefined'.   console.log(student.name + ` , ${student.age.toString()}`);    // Confirming that student.age is not null   console.log(student.name + ` , ${student.age!.toString()}`);    // Condition is checked that student's age isn't null   if (student.age != null) {     console.log(student.name + ` , ${student.age.toString()}`);   } }  let obj: Student = { name: "sean", age: 20 }; console.log(displayStudentInfo(obj)); 

Output: 

sean , 20  sean , 20  sean , 20

Next Article
How to Check Types in Typescript?
author
isitapol2002
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • Geeks Premier League
  • TypeScript
  • Geeks-Premier-League-2022

Similar Reads

  • How to declare nullable type in TypeScript ?
    In vanilla JavaScript, there are two primary data types: null and undefined. While TypeScript previously did not allow explicit naming of these types, you can now use them regardless of the type-checking mode. To assign undefined to any property, you need to turn off the --strictNullChecks flag. How
    2 min read
  • How to check interface type in TypeScript ?
    Typescript is a pure object-oriented programming language that consists of classes, interfaces, inheritance, etc. It is strict and it statically typed like Java. Interfaces are used to define contacts in typescript. In general, it defines the specifications of an entity. Below is an example of an in
    2 min read
  • How to Convert a String to enum in TypeScript?
    In TypeScript, an enum is a type of class that is mainly used to store the constant variables with numerical and string-type values. In this article, we will learn, how we can convert a string into an enum using TypeScript. These are the two approaches that can be used to solve it: Table of Content
    5 min read
  • How to Check if an Object is Empty in TypeScript ?
    In TypeScript, it's common to encounter scenarios where you need to determine if an object is empty or not. An empty object typically means it contains no properties or all its properties are either undefined or null. Below are the methods to check if an object is empty or not in TypeScript: Table o
    3 min read
  • How to Check Types in Typescript?
    Checking types in TypeScript involves methods like typeof for primitive types, instanceof for class instances, and custom type guards for complex type validation. These techniques help ensure variables are correctly typed, improving code safety, and readability, and preventing runtime errors.Here ar
    3 min read
  • How to check null and undefined in TypeScript ?
    In this article let's learn how to check if a variable is null or undefined in TypeScript. A variable is undefined when it's not assigned any value after being declared. Null refers to a value that is either empty or doesn't exist. null means no value. To make a variable null we must assign null val
    3 min read
  • How to Convert String to Boolean in TypeScript ?
    In Typescript, sometimes you receive the data as strings but need to work with boolean values or identify the boolean equivalent of it. There are several approaches to convert string to boolean in TypeScript which are as follows: Table of Content Using Conditional StatementUsing JSON.parse() MethodU
    4 min read
  • How to define Singleton in TypeScript?
    In this article, we will learn about the Singleton in TypeScript. A singleton is a class that always has only one instance of it at the global level. If more than one instance is created then they all will refer to the same instance and changes in the properties of one instance will reflect in the p
    3 min read
  • How to Create Deep Readonly Type in Typescript?
    In TypeScript, the readonly access modifier is a powerful tool that ensures immutability by marking properties of a class as immutable. Once a property is markedreadonly, it cannot be reassigned. This is highly useful for maintaining consistent and safe data structures, especially in scenarios such
    3 min read
  • How To Use @ts-ignore For A Block In TypeScript?
    The @ts-ignore is a compiler that lets the compiler ignore the line below it which is like a directive used to suppress TypeScript compiler errors upcoming on the next line of the whole code. This is mostly used when we as the developers know the code is good and useful but the compiler flags it as
    3 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