microsoft / microsoft/TypeScript

Narrow number literal types with comparison

Offen
#36,099 2 Kommentare 11 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

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

Beschreibung

Search Terms

constant number literals narrowing comparison

Suggestion

Narrow number literal type not only with (non)equality, but also with less-than etc.
This request is only about throwing away non-matching literals, and not about full-blown number narrowing.

Use Cases

This could be used to direct narrowing with tuple unions.

Examples

With literals

type X = 0 | 1 | 2 | 3;
function f(): X {
    return 1;
}
function g(x: 0 | 3) { 
    console.log(x);
}
let x: X = f();
g(x); // Error, 1 | 2 is unexpected
if (x > 2) { 
    g(x); // Same error, but should be safe
}
if (x != 1 && x != 2) { 
    g(x); // Ok
}

With tuples

type X = [] | [string, string];
function f(): X { return [];}
function g(x: string) { 
    console.log(x);
}
let x: X = f();
g(x[0]); // Error, undefined is unexpected
if (x.length > 0) { 
    g(x[0]); // Error, but should be ok
}
if (x.length == 2) { 
    g(x[0]); // Ok
}

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, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

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.

Rechercherichtung

Beginne mit den Literal- und Tupelbeispielen im Issue und reproduziere deren aktuelle Diagnosemeldungen und ihr Narrowing-Verhalten. Definiere die erwarteten Kontrollflussergebnisse für Vergleichsprüfungen, einschließlich Kleiner-als- und Tupellängenvergleichen, und verifiziere, dass die Änderung nur unmögliche Literal-Fälle entfernt, ohne ein allgemeines Zahlen-Narrowing einzuführen.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
typescript
Bereich
compilers
Issue-Typ
Feature
Schwierigkeit
5/5
Geschätzter Aufwand
Über eine Woche
Aktivitätsstatus
Veraltet
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
35/100

Neue Issues direkt in Ihr Postfach

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