TS7030
error TS7030: Not all code paths return a value.
Broken Code ❌
1 2 3 4 5
| function getFlightType(type: 1 | 2) { if (type === 1) { return 'Return trip'; } }
|
Fixed Code ✔️
TypeScript reminds us that we forgot to return a value in case our if-condition doesn’t match. We can solve this problem in many ways.
Always return a value:
1 2 3 4 5 6
| function getFlightType(type: 1 | 2) { if (type === 1) { return 'Return trip'; } return 'One way'; }
|
Add general else
:
1 2 3 4 5 6 7
| function getFlightType(type: 1 | 2) { if (type === 1) { return 'Return trip'; } else { return 'One way'; } }
|
Handle all cases
:
1 2 3 4 5 6 7 8
| function getFlightType(type: 1 | 2) { switch (type) { case 1: return 'Return trip'; case 2: return 'One way'; } }
|
Add default
case:
1 2 3 4 5 6 7 8
| function getFlightType(type: 1 | 2) { switch (type) { case 1: return 'Return trip'; default: return 'One way'; } }
|
Define that the return type can be void
:
1 2 3 4 5
| function getFlightType(type: 1 | 2): string | void { if (type === 1) { return 'Return trip'; } }
|
Video Tutorial