TS2377
TypeScriptERRORCommonClassesHIGH confidence

A 'return' statement can only be used within a function body.

What this means

A 'return' statement was found inside a class constructor. Constructors implicitly return the class instance and cannot have an explicit return statement.

Why it happens
  1. 1Placing a 'return' statement inside a constructor.
  2. 2Mistaking a constructor for a regular method.
  3. 3Attempting to return a different object from the constructor, which is not allowed in TypeScript for constructors.
How to reproduce

A class constructor contains a return statement.

trigger — this will error
trigger — this will error
class MyClass {
  constructor() {
    return 1;
  }
}

expected output

error TS1108: A 'return' statement can only be used within a function body.

Fix 1

Remove the return statement

WHEN The return statement is not needed.

Remove the return statement
class MyClass {
  constructor() {
    // Initialization logic here
  }
}

Why this works

Constructors automatically return the new instance, so an explicit return is unnecessary.

Fix 2

Move the logic to a method

WHEN A value needs to be returned based on initialization.

Move the logic to a method
class MyClass {
  private value: number;
  constructor() {
    this.value = 1;
  }
  getValue(): number {
    return this.value;
  }
}

Why this works

Encapsulating the logic in a method allows for a return value while keeping the constructor clean.

What not to do

Try to return a different object from the constructor

This pattern is disallowed in TypeScript and JavaScript classes; the constructor's job is solely to initialize the instance ('this').

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