microsoft / microsoft/TypeScript

"Holey" behavior on differently-typed getter/setter properties

Aperta
#43,462 6 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

In Discussion Suggestion
Lingua principale
Go
Stelle
111k
Fork
14.4k
Merge medio
1g 19h
PR unite (30g)
117

Descrizione

I was asked to provide an example of separate read/write types that doesn't necessarily use classes, and here's what I ended up finding. 😅

Take the following:

interface Thing {
    get name(): string
    set name(value: string | null | undefined);
}

function makeThing(): Thing {
    let name = "";
    return {
        get name() {
            return name;
        },
        set name(value) {
            name = value.toString();
        }
    }
}

In this example, you might think that you're writing type-safe code, but in fact you've got a bug. Our get/set accessors don't have type annotations, so TypeScript assumes the name setter has the type string. Because only the reading type of the name property is validated against Thing, TypeScript thinks that the given object conforms to the type Thing; however, a user can pass write a null or undefined, and a user won't know that they haven't handled it correctly.

This was one of the known tradeoffs when we implemented this feature - we acknowledged this. But I hit this surprisingly quickly. It seems like if you're using this pattern without classes, it's pretty easy to run into this issue.

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

Riproduci il problema con l'interfaccia Thing fornita e l'esempio makeThing, quindi esamina il controllo delle proprietà getter/setter di TypeScript. Nel report non sono indicati né un file sorgente né un test; per procedere sarebbe necessario decidere il comportamento previsto e aggiungere una copertura per le scritture di null e undefined.

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

Valutazione

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

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.