Strict null checks help catch mistakes where a value might be missing or empty. This keeps your program safe and avoids crashes.
Strict null checks and safety in Typescript
{
"compilerOptions": {
"strictNullChecks": true
}
}
// Example variable declaration
let name: string | null = null;
// Checking before use
if (name !== null) {
console.log(name.toUpperCase());
}Setting strictNullChecks to true makes TypeScript check for null and undefined values strictly.
You must check if a value is null or undefined before using it, or TypeScript will show an error.
let age: number | null = null; age = 25; if (age !== null) { console.log(age + 1); }
function greet(name: string | undefined) { if (name) { console.log(`Hello, ${name}!`); } else { console.log("Hello, guest!"); } }
data.length without checking causes an error with strict null checks.let data: string | null = null; // Error if strictNullChecks is true: // console.log(data.length); // Correct way: if (data !== null) { console.log(data.length); }
This program prints the length of a string if it exists, or a message if it is null.
function printLength(text: string | null) { if (text === null) { console.log("No text provided."); } else { console.log(`Length: ${text.length}`); } } printLength(null); printLength("Hello");
Always check for null or undefined before using values when strict null checks are on.
You can use ! (non-null assertion) to tell TypeScript a value is not null, but use it carefully.
Strict null checks make your code safer and easier to maintain.
Strict null checks help prevent errors by forcing you to handle null and undefined values.
Use checks like if (value !== null) before using values that can be null.
This feature makes your TypeScript code more reliable and clear.
Practice
What does enabling strictNullChecks in TypeScript do?
Solution
Step 1: Understand strictNullChecks purpose
EnablingstrictNullChecksmakes TypeScript require explicit handling ofnullandundefinedvalues to avoid runtime errors.Step 2: Analyze options
Only It forces you to explicitly handlenullandundefinedvalues. correctly describes this behavior. Options B, C, and D are incorrect because they describe behaviors thatstrictNullChecksdoes not do.Final Answer:
It forces you to explicitly handlenullandundefinedvalues. -> Option DQuick Check:
strictNullChecks = explicit null handling [OK]
- Thinking nulls are automatically converted
- Assuming null checks are disabled
- Believing null can be assigned anywhere
Which of the following is the correct way to check for null or undefined before accessing a variable value in TypeScript with strictNullChecks enabled?
let value: string | null | undefined;
Solution
Step 1: Understand null and undefined checks
WithstrictNullChecks, you must check bothnullandundefinedexplicitly before accessing properties.Step 2: Evaluate each option
if (value !== null && value !== undefined) { console.log(value.length); } correctly checks bothnullandundefined. if (value) { console.log(value.length); } may fail ifvalueis an empty string. console.log(value.length); causes an error. if (value == null) { console.log(value.length); } checks for null but then accesses length inside the if, which is incorrect logic.Final Answer:
if (value !== null && value !== undefined) { console.log(value.length); } -> Option AQuick Check:
Check both null and undefined explicitly [OK]
- Using only if(value) which fails on empty strings
- Accessing properties without checks
- Using == null but then accessing inside that block
What will be the output of the following TypeScript code with strictNullChecks enabled?
function greet(name: string | null) {
if (name === null) {
return "Hello, guest!";
}
return `Hello, ${name.toUpperCase()}!`;
}
console.log(greet(null));
console.log(greet("alice"));Solution
Step 1: Analyze null check in function
The function checks ifname === nulland returns "Hello, guest!" in that case, so it safely handles null.Step 2: Check outputs for calls
Callinggreet(null)returns "Hello, guest!". Callinggreet("alice")returns "Hello, ALICE!" becausetoUpperCase()is called on a string.Final Answer:
"Hello, guest!" and "Hello, ALICE!" -> Option BQuick Check:
Null check prevents errors, outputs as expected [OK]
- Expecting runtime error on null
- Thinking compilation error occurs
- Ignoring null check and causing error
Identify the error in this TypeScript code with strictNullChecks enabled and suggest a fix:
function printLength(text: string | null) {
console.log(text.length);
}Solution
Step 1: Identify the error
Accessingtext.lengthwithout checking iftextisnullcauses a compile error understrictNullChecks.Step 2: Suggest fix
Add a check likeif (text !== null)before accessinglengthto ensure safety.Final Answer:
Error: Object is possibly 'null'. Fix: Add a null check before accessinglength. -> Option AQuick Check:
Always check null before property access [OK]
- Ignoring null check and expecting no error
- Changing type instead of fixing code
- Thinking return type causes error
Given this TypeScript function with strictNullChecks enabled, which modification safely handles undefined and null inputs without errors?
function formatName(name: string | null | undefined) {
return name.toUpperCase();
}Solution
Step 1: Identify unsafe code
CallingtoUpperCase()onnamewithout checking fornullorundefinedcauses errors withstrictNullChecks.Step 2: Evaluate options for safety
Add a check:if (name == null) return "Unknown";before callingtoUpperCase(). adds a check for bothnullandundefined(using== null) and returns a default string, safely avoiding errors. Change parameter type tostringonly and remove null and undefined. removes null safety but is less flexible. Use non-null assertion:return name!.toUpperCase();forces non-null assertion which can cause runtime errors. RemovestrictNullChecksfrom tsconfig. disables safety feature, not recommended.Final Answer:
Add a check:if (name == null) return "Unknown";before callingtoUpperCase(). -> Option CQuick Check:
Check null/undefined before method calls [OK]
- Using non-null assertion unsafely
- Removing null from type instead of checking
- Disabling strictNullChecks instead of fixing code
Ready to prove it?
Pass the test and this pattern moves unknown
