TS2366
TypeScriptERRORNotableFunctionsHIGH confidence

Function lacks ending return statement and return type does not include 'undefined'.

What this means

A function is declared with a specific return type, but not all code paths within the function return a value of that type.

Why it happens
  1. 1A conditional branch (if/else) is missing a return statement.
  2. 2The function has a declared return type but has no return statement at all.
  3. 3An early exit from the function (like throwing an error) is not accounted for in all paths.
How to reproduce

A function with a 'string' return type has a code path that does not return anything.

trigger — this will error
trigger — this will error
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.

Add a return statement to all code paths
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.

Modify the return type to include 'undefined'
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'.

What not to do

Remove the return type annotation

This makes the function's return type implicit ('any' or inferred), which reduces type safety and clarity.

Sources
Official documentation ↗

microsoft/TypeScript src/compiler/diagnosticMessages.json

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All TypeScript errors