TS7030
Not all code paths return a value.
Broken Code ❌
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:
function getFlightType(type: 1 | 2) {
if (type === 1) {
return 'Return trip';
}
return 'One way';
}Add general else:
function getFlightType(type: 1 | 2) {
if (type === 1) {
return 'Return trip';
} else {
return 'One way';
}
}Handle all cases:
function getFlightType(type: 1 | 2) {
switch (type) {
case 1:
return 'Return trip';
case 2:
return 'One way';
}
}Add default case:
function getFlightType(type: 1 | 2) {
switch (type) {
case 1:
return 'Return trip';
default:
return 'One way';
}
}Define that the return type can be void:
function getFlightType(type: 1 | 2): string | void {
if (type === 1) {
return 'Return trip';
}
}