microsoft / microsoft/TypeScript

Cannot bracket-index into an object after checking it's existence on that object.

Offen
#44,117 4 Kommentare 0 Reaktionen 1 zugewiesene Person Auf GitHub ansehen

@DanielRosenwasser arbeitet bereits daran.

Seit 20.5.2021.

Breaking Change
Vorherrschende Sprache
Go
Sterne
111k
Forks
14.3k
Ø Merge
2 T. 4 Std.
Gemergte PRs (30 T.)
132

Beschreibung

Bug Report

Cannot bracket-index into an object after checking it's existence on that object.

The same failure was reported in #43651, but I couldn't find a separate discussion or a ticket for this.

🔎 Search Terms
  • implicitly has an 'any' type
  • bracket indexing
🕗 Version & Regression Information

Worked in 4.2.4. Starts to break since 4.3.0-beta

⏯ Playground Link

Playground link

💻 Code
interface A {}
function foo(a:A) {
    if ('abc' in a) {
        const z = a;
        // Element implicitly has an 'any' type because expression of type '"abc"' can't be used to index type 'A'.
        // Property 'abc' does not exist on type 'A'.
        return z['abc']; 
    }
}
🙁 Actual behavior

Compiler gives an error that you cannot index into type 'A', since 'abc' does not exist in type 'A'

🙂 Expected behavior

Compiler recognizes the existence check and does not give an error.

Observation

This seems to be caused by the improvement in the control flow analysis/type inference. Before the type of z in the below example was 'never' prior to TS4.3, but now the compiler recognizes z being type A

Question : I have one question though, is it by design that it's allowed to index into never types?

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Bewertung

Dieses Issue wurde noch nicht bewertet.

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.