Nullable Types ('strictNull')
Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 71 of 73.
By default, TypeScript allows null and undefined to be assigned to any type, which can lead to runtime errors. The strictNullChecks compiler option changes this behavior by making null and undefined their own distinct types.
When strictNullChecks is enabled, you must explicitly include null or undefined in your type annotations if you want to allow these values:
// Without strictNullChecks - this would be allowed
let name: string = null; // Error with strictNullChecks!
// With strictNullChecks - you must be explicit
let name: string | null = null; // Now this worksThis forces you to handle potential null values before using them. You cannot call methods or access properties on a value that might be null without first checking:
function processName(name: string | null) {
// This would cause an error
// console.log(name.toUpperCase());
// You must check first
if (name !== null) {
console.log(name.toUpperCase()); // Safe to use
}
}This compiler option helps prevent the common "Cannot read property of null" runtime errors by catching them at compile time, making your code more reliable and predictable.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyCreate a function that safely processes user profile data that might contain null values. This challenge demonstrates how strictNullChecks forces you to handle nullable types explicitly.
Create a function named getUserDisplayName that:
- Takes a parameter
fullNameof typestring | null - Returns the full name if it's not
null - Returns
"Anonymous User"if the full name isnull - Has an explicit return type of
string
Create a second function named formatUserEmail that:
- Takes a parameter
emailof typestring | null - Returns the email in lowercase if it's not
null - Returns
"No email provided"if the email isnull - Has an explicit return type of
string
Create a third function named getUserInfo that:
- Takes two parameters:
nameof typestring | nullandemailof typestring | null - Uses both previous functions to process the parameters
- Returns a formatted string:
"Name: [processed name], Email: [processed email]" - Has an explicit return type of
string
Test your functions with the following data:
- Call
getUserDisplayName("John Smith")and print the result - Call
getUserDisplayName(null)and print the result - Call
formatUserEmail("ALICE@EXAMPLE.COM")and print the result - Call
formatUserEmail(null)and print the result - Call
getUserInfo("Bob Johnson", "bob@test.com")and print the result - Call
getUserInfo(null, null)and print the result - Call
getUserInfo("Sarah Wilson", null)and print the result
Cheat sheet
The strictNullChecks compiler option makes null and undefined their own distinct types, preventing runtime errors by catching null-related issues at compile time.
With strictNullChecks enabled, you must explicitly include null or undefined in type annotations:
// Error with strictNullChecks
let name: string = null;
// Correct - explicit null type
let name: string | null = null;You must check for null values before using them:
function processName(name: string | null) {
// Must check first
if (name !== null) {
console.log(name.toUpperCase()); // Safe to use
}
}Try it yourself
// TODO: Write your code here
// Create the getUserDisplayName function that takes fullName (string | null) and returns string
// Create the formatUserEmail function that takes email (string | null) and returns string
// Create the getUserInfo function that takes name and email (both string | null) and returns string
// Test the functions and print the results
console.log(getUserDisplayName("John Smith"));
console.log(getUserDisplayName(null));
console.log(formatUserEmail("ALICE@EXAMPLE.COM"));
console.log(formatUserEmail(null));
console.log(getUserInfo("Bob Johnson", "bob@test.com"));
console.log(getUserInfo(null, null));
console.log(getUserInfo("Sarah Wilson", null));This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Introduction To TypeScript
1Getting Started with TS
What is TypeScript?Why Use TypeScript?Your First TypeScript CodeCompilation Process & ErrorsRecap: Introduction to TS4Working with Functions
Typing Params & Return ValuesTyping Arrow FunctionsThe 'void' Return TypeOptional Parameters with '?'Default Parameter ValuesTyping Rest ParametersDefining Function TypesRecap: Building Typed Funcs2Core Types
Basic Types: str, num, booleanThe 'any' Type: Escape HatchThe 'unknown' TypeWorking with 'null' & 'undef'Type Inference in ActionExplicit Type AnnotationsRecap: Core Types Practice5Types: Aliases, Unions & Inter
Type Aliases for PrimitivesUnion Types ('|')Working with Union TypesLiteral TypesIntersection Types ('&')Combining Type AliasesRecap: Advanced Type Combos8Enums
What is a Numeric Enum?Using Numeric EnumsWhat is a String Enum?Using String EnumsHeterogeneous EnumsRecap: Using Enums11Advanced Topics
Type Assertions Type Guards: in & instanceofThe 'never' TypeNullable Types ('strictNull')Index Signatures for ObjectsRecap: Fine-Tuning Types3Data Structure: Arrays & Tuple
Typed Arrays'readonly' Modifier for ArraysWhat is a Tuple?Declaring and Accessing TuplesDestructuring TuplesReadonly TuplesMulti-dimensional Typed Arrays Spread Operator with ArraysRecap: Arrays and Tuples