microsoft / microsoft/TypeScript

TS2333: 'this' cannot be referenced in constructor arguments

Aperta
#42,580 1 commento 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Awaiting More Feedback Suggestion
Lingua principale
Go
Stelle
111k
Fork
14.3k
Merge medio
2g 4h
PR unite (30g)
132

Descrizione

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.

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia tracciando la diagnosi TS2333 e i controlli del compilatore per this negli argomenti del costruttore; l'issue non indica file o test specifici. Confronta gli esempi di costruttori proposti con il JavaScript emesso e con il comportamento esistente del controllo dei tipi, e considera test che stabiliscano quando il riferimento dovrebbe essere accettato senza modificare l'output a runtime.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
typescript
Ambito
compilers
Tipo di issue
Funzionalità
Difficoltà
5/5
Tempo stimato
Più di una settimana
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
25/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.