microsoft / microsoft/TypeScript
TS2333: 'this' cannot be referenced in constructor arguments
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
Suggestion
✅ Viability Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
⭐ Suggestion
TypeScript disallows this:
class A {
constructor(readonly b: B = new B(this)) {}
}
class B {
constructor(a: A) {}
}
TS2333: 'this' cannot be referenced in constructor arguments
Instead, we can rewrite it as follows.
class A {
readonly b: B;
constructor(b?: B) {
this.b = b ?? new B(this);
}
}
class B {
constructor(a: A) {}
}
However, this is clearly more verbose. Since this transformation is always possible, it seems TypeScript should allow this in the constructor and be doing the job of rewriting it for us, so we can maintain simpler code using the former constructor argument approach.
📃 Motivating Example
Permitting this references in constructor arguments simplifies object initialization.
💻 Use Cases
Creating classes at construction time that reference the creating class.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by tracing the TS2333 diagnostic and the compiler's checks for this in constructor arguments; the issue does not name specific files or tests. Compare the proposed constructor examples with emitted JavaScript and existing type-checking behavior, and consider tests that establish when the reference should be accepted without changing runtime output.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100