Nullable Types in TypeScript (Live Playground)
In this tutorial, we will explore nullable types and strict null checks in TypeScript, which help you create more robust and error-free code.
Nullable Types
In TypeScript, nullable types are types that can have a value of null
in addition to their usual values. Nullable types are useful for representing optional properties or values that can be missing or uninitialized.
By default, TypeScript allows null
and undefined
values for all types, which can lead to unintentional errors.
Strict Null Checks
TypeScript introduces a compiler flag called strictNullChecks
that enforces stricter type checking for null
and undefined
. When this flag is enabled, the compiler ensures that you explicitly handle null
and undefined
values in your code.
To enable strict null checks, add the following to your tsconfig.json
:
{
"compilerOptions": {
"strictNullChecks": true
}
}
Using Nullable Types
With strict null checks enabled, you will need to handle nullable types explicitly in your code.
Optional Properties
interface Person {
name: string;
age?: number; // The age property is optional
}
function greet(person: Person): string {
return `Hello, ${person.name}!${person.age ? ` You are ${person.age} years old.` : ''}`;
}
console.log(greet({ name: 'John', age: 25 })); // Hello, John! You are 25 years old.
console.log(greet({ name: 'Jane' })); // Hello, Jane!
In this example, the age
property is marked as optional using the ?
syntax. This means that it can be undefined
when not provided.
Union Types with null
type NullableString = string | null;
function getGreeting(name: NullableString): string {
return name ? `Hello, ${name}!` : 'Hello, guest!';
}
console.log(getGreeting('John')); // Hello, John!
console.log(getGreeting(null)); // Hello, guest!
In this example, we define a NullableString
type that can be a string
or null
. This allows us to handle cases where the name might not be provided.
Conclusion
In this tutorial, we explored nullable types and strict null checks in TypeScript, which help you create more robust and error-free code. As you continue learning TypeScript, consider enabling strict null checks in your projects to enforce better handling of null
and undefined
values.