TS Null
The null
type in TypeScript represents a variable that has been explicitly set to no value. It is useful for indicating the intentional absence of an object value.
Key Topics
Null Basics
In TypeScript, null
is a value that represents the intentional absence of any object value.
let value: null = null;
console.log(value); // null
Output
null
Explanation: The variable value
is explicitly assigned the null
value, indicating the absence of a value.
Strict Null Checks
When strictNullChecks
is enabled in TypeScript, null
and undefined
are not assignable to other types unless explicitly stated.
// strictNullChecks: true
let nullable: string | null = null;
nullable = "TypeScript";
console.log(nullable); // TypeScript
Output
TypeScript
Explanation: The nullable
variable can hold a value of type string
or null
due to the explicit union type declaration.
Optional Properties
Optional properties in interfaces or types are implicitly undefined
if not assigned, but they can be explicitly set to null
if needed.
interface User {
id: number;
name?: string | null;
}
const user: User = { id: 1, name: null };
console.log(user); // { id: 1, name: null }
Output
{ id: 1, name: null }
Explanation: The name
property in the User
interface is optional and can explicitly hold a null
value.
Nullish Coalescing
The ??
operator, known as the nullish coalescing operator, returns its right-hand operand when the left-hand operand is null
or undefined
.
const input = null;
const result = input ?? "Default Value";
console.log(result); // Default Value
Output
Default Value
Explanation: The result
variable is assigned "Default Value"
because input
is null
. The nullish coalescing operator ensures fallback values are used for null
or undefined
.
Key Takeaways
- Null Basics:
null
represents the intentional absence of a value. - Strict Null Checks: Prevent assigning
null
orundefined
to variables unless explicitly allowed. - Optional Properties: Use
null
for explicitly indicating no value in optional properties. - Nullish Coalescing: Use the
??
operator to handlenull
orundefined
values gracefully.