TS2366

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

Broken Code ❌

1
2
3
4
5
6
7
8
export function getInterestRate(years: 1 | 2 | 3): number {
switch (years) {
case 1:
return 1.75;
case 2:
return 2.96;
}
}

Fixed Code ✔️

The switch-case statement isn’t handling all cases from every possible input. We can solve that by defining a default case:

1
2
3
4
5
6
7
8
9
10
export function getInterestRate(years: 1 | 2 | 3): number {
switch (years) {
case 1:
return 1.75;
case 2:
return 2.96;
default:
return 3;
}
}

Another solution would be to implement the missing case for 3:

1
2
3
4
5
6
7
8
9
10
export function getInterestRate(years: 1 | 2 | 3): number {
switch (years) {
case 1:
return 1.75;
case 2:
return 2.96;
case 3:
return 3;
}
}

Video Tutorial