Table of contents

  1. 1. Video
  2. 2. Final Code
  3. 3. Summary

In this tutorial Benny shows you simple techniques on how to improve your switch statements. Using the tips and tricks from the video, you will never miss a switch case again. You will also learn how to fix error TS2322, TS2366 and TS7030.

Video

Errors fixed in the video:

TS2322: Type ‘undefined’ is not assignable to type ‘number’.

TS2366: Function lacks ending return statement and return type does not include ‘undefined’.

TS7030: Not all code paths return a value.

Final Code

LoanCalculator.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
export enum LoanTerm {
ONE_YEAR = 'ONE_YEAR',
TWO_YEARS = 'TWO_YEARS',
THREE_YEARS = 'THREE_YEARS',
FOUR_YEARS = 'FOUR_YEARS',
FIVE_YEARS = 'FIVE_YEARS'
}

export interface Loan {
term: LoanTerm,
type: 'AUTO_LOAN' | 'HOME_LOAN' | 'REFINANCING'
}

export type InterestRate = 1.75 | 2.96 | 3.5 | 5;

export function getInterestRate(loan: Loan): InterestRate {
switch (loan.term) {
case LoanTerm.ONE_YEAR:
return 1.75;
case LoanTerm.TWO_YEARS:
case LoanTerm.THREE_YEARS:
return 2.96;
case LoanTerm.FOUR_YEARS:
return 3.5;
case LoanTerm.FIVE_YEARS:
return 5;
}
}

const interestRate = getInterestRate({term: LoanTerm.ONE_YEAR, type: 'AUTO_LOAN'});

Summary