microsoft / microsoft/TypeScript

Narrow number literal types with comparison

Aperta
#36,099 2 commenti 11 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

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

Descrizione

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.

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 con gli esempi di literal e tuple nell’issue, riproducendo le diagnostiche attuali e il relativo comportamento di narrowing. Definisci i risultati attesi del flusso di controllo per i controlli dei confronti, inclusi i confronti less-than e quelli della lunghezza delle tuple, e verifica che la modifica rimuova solo i casi di literal impossibili senza introdurre un narrowing generale dei numeri.

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
35/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.