A 'return' statement can only be used within a function body.
A 'return' statement was found inside a class constructor. Constructors implicitly return the class instance and cannot have an explicit return statement.
- 1Placing a 'return' statement inside a constructor.
- 2Mistaking a constructor for a regular method.
- 3Attempting to return a different object from the constructor, which is not allowed in TypeScript for constructors.
A class constructor contains a return statement.
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.
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.
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.
✕ 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').
microsoft/TypeScript src/compiler/diagnosticMessages.json
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev