Function lacks ending return statement and return type does not include 'undefined'.
A function is declared with a specific return type, but not all code paths within the function return a value of that type.
- 1A conditional branch (if/else) is missing a return statement.
- 2The function has a declared return type but has no return statement at all.
- 3An early exit from the function (like throwing an error) is not accounted for in all paths.
A function with a 'string' return type has a code path that does not return anything.
function getValue(key: string): string {
if (key === "name") {
return "Alice";
}
// No return here
}expected output
error TS2366: Function lacks ending return statement and return type 'string' does not include 'undefined'.
Fix 1
Add a return statement to all code paths
WHEN A path is missing a return.
function getValue(key: string): string {
if (key === "name") {
return "Alice";
}
return "Default"; // Added return
}Why this works
Ensuring every possible execution path concludes with a return statement that provides a value of the declared type.
Fix 2
Modify the return type to include 'undefined'
WHEN The function is intentionally designed to sometimes return nothing.
function getValue(key: string): string | undefined {
if (key === "name") {
return "Alice";
}
// Implicitly returns undefined
}Why this works
A union type makes it explicit that the function can return a value of the specified type or 'undefined'.
✕ Remove the return type annotation
This makes the function's return type implicit ('any' or inferred), which reduces type safety and clarity.
microsoft/TypeScript src/compiler/diagnosticMessages.json
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev