Summary - Strict mode
- TypeScript course
- Beginner
- Lesson 70/89
- 4 min
Write a safe account program by enabling strict options.
Summary - Safe account with strict mode
Turning on strict: true in an account program brings many protections at once, such as null safety and strict function types. An account may be null; we express this with Account | null and check for null in every operation.
interface Account { id: string; balance: number; }
function deposit(acc: Account | null, amount: number): Account {
if (acc === null) {
return { id: "yeni", balance: amount };
}
return { id: acc.id, balance: acc.balance + amount };
}Practice Safe account program
Define an Account interface: id: string and balance: number. Write a function deposit(acc: Account | null, amount: number): Account: if acc is null, return a new account (id: "yeni", balance: amount); otherwise update the balance with acc.balance + amount. Print two examples.
Starter code
// Account arayüzünü tanımla: id ve balance
// deposit(acc: Account | null, amount: number): Account döndürür
// acc null ise yeni hesap: id "yeni", balance = amount
// değilse balance'a amount ekle
// iki örneği yazdırSample solution
interface Account {
id: string;
balance: number;
}
function deposit(acc: Account | null, amount: number): Account {
if (acc === null) {
return { id: "yeni", balance: amount };
}
return { id: acc.id, balance: acc.balance + amount };
}
console.log(deposit(null, 100).balance);
console.log(deposit({ id: "a1", balance: 50 }, 30).balance);Expected output
100 80
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which of the following strict options provides null safety?
- alwaysStrict
- noImplicitAny
- strictNullChecks Correct answer
- strictFunctionTypes
Explanation: strictNullChecks makes null and undefined separate from other types, providing null safety.
2 Nullable account handler
type AccountHandler = (acc: Account ____ ) => void;
type AccountHandler = (acc: Account | null ) => void;
Explanation: Since an account may be null, the handler parameter should be Account | null. & is intersection, | undefined is a different absent type, and ? null is invalid syntax.
3 Strict mode account parts
| Term | Meaning |
|---|---|
strict: true |
Enables all options at once |
Account | null |
An account type that can be null |
acc === null |
Narrowing via null check |
acc.balance + amount |
Balance update |