strictNullChecks
- TypeScript course
- Beginner
- Lesson 68/89
- 4 min
Learn the option that enforces null safety.
What is strictNullChecks?
With strictNullChecks on, null and undefined become separate from other types. You cannot assign null to a string variable; you must write string | null for it to accept null. This prevents runtime null-read errors.
let t: string | null = null;
if (t !== null) {
console.log(t.length); // safe access
}When strictNullChecks is off
With strictNullChecks off, null and undefined are assignable to any type. This flexibility is dangerous; if you access a property without checking for null, the app may crash.
let s: string = null; // valid when off
console.log(s.length); // runtime errorWith it on, this line fails at compile time and you see the error early.
Practice Null-safe first element
Write a function firstOrNull(arr: string[]): string | null. If the array is empty, return null; otherwise return the first element. Print the result of both calls.
Starter code
// firstOrNull(arr: string[]): string | null döndürür
// dizi boş ise null döndür
// değilse ilk elemanı döndür
// iki çağrıyı da yazdırSample solution
function firstOrNull(arr: string[]): string | null {
if (arr.length === 0) {
return null;
}
return arr[0];
}
console.log(firstOrNull(["a", "b"]));
console.log(firstOrNull([]));Expected output
a null
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which assignment is valid when strictNullChecks is on?
- let s: string = null;
- let s: string; s = null;
- let s: string = undefined;
- let s: string | null = null; Correct answer
Explanation: With strictNullChecks on, you cannot assign null or undefined to a string variable. Writing string | null explicitly makes the null assignment valid.
2 Nullable return type
function getName(): string ____ { return null; }
function getName(): string | null { return null; }
Explanation: With strictNullChecks on, you cannot return null from a string function. Writing string | null lets the function return null.
3 strictNullChecks parts
| Term | Meaning |
|---|---|
strictNullChecks |
Makes null and undefined separate types |
string | null |
A string that can be null |
string |
Cannot be null under strict mode |
t !== null |
Type narrowing |