How could you check null and undefined in TypeScript?
How could you check null and undefined in TypeScript?
In TypeScript, checking for null
and undefined
values is a common task, as these values often represent the absence of a value or uninitialized variables. There are several methods to check for these values effectively:
==
and ===
)Loose Equality (==
): Using ==
checks for both null
and undefined
simultaneously. This is because null
and undefined
are loosely equal to each other.
if (value == null) {
// This will be true if value is null or undefined
}
Strict Equality (===
): Using ===
provides a strict check against either null
or undefined
, meaning it checks both the value and the type.
if (value === null) {
// This will be true only if value is exactly null
}
if (value === undefined) {
// This will be true only if value is exactly undefined
}
typeof: You can use the typeof
operator to check specifically for undefined
.
if (typeof value === 'undefined') {
// This will be true only if value is undefined
}
Type Guard Functions: Custom type guard functions can be defined to check for null
or undefined
.
function isNullOrUndefined(value: any): value is null | undefined {
return value === null || typeof value === 'undefined';
}
??
)Introduced in TypeScript 3.7, the nullish coalescing operator (??
) is a logical operator that returns its right-hand side operand when its left-hand side operand is null
or undefined
, and otherwise returns its left-hand side operand.
const result = value ?? "default value";
// If value is null or undefined, result will be "default value"
?.
)Optional chaining (?.
) allows you to safely access deeply nested properties of an object without having to explicitly check if each reference in the chain is nullish (null
or undefined
).
const nestedValue = obj?.prop?.nestedProp;...
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào