microsoft / microsoft/TypeScript

Evaluate mathematical expression of indices when indexing tuples

Aperta
#42,693 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
1g 19h
PR unite (30g)
117

Descrizione

Suggestion

🔍 Search Terms

tuple bounds, tuple index computing, bound checking removal, noUncheckedIndexedAccess

✅ 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

Currently (version 4.1), Typescript is able to deduce that an array access to a tuple is within bounds if it is indexed by an integer literal union type that fits within the array, e.g.:

type I = 0 | 1 | 2;
function access(i: I, a: [string, string, string]) {
    return a[i];
} // type: string, even with noUncheckedIndexedAccess = true

However, as soon as there is an operation on the indexing variable, even trivial, Typescript falls back to inferring number. Therefore, the following code:

type I = 0 | 1;
function access(i: I, a: [string, string, string]) {
    return a[i + 1];
} // type: string | undefined, when noUncheckedIndexedAccess = true

In principle, Typescript could reason a bit deeper on the set of possible integer values when going through operations, especially for the trivial ones like in my example. If there is a lot of values in the union, it might be computationally expensive, but in that case a conservative bound analysis would already be enough for most uses cases (see #15480).

📃 Motivating Example

The proposed feature would at minimum allow:

type I = 0 | 1;
function access(i: I, a: [string, string, string]) {
    return a[i + 1];
}

and, if possible, use cases such as:

type Vector = [number, number];
type Matrix = [number, number, number, number];
const Range = [0, 1] as const;
function mult(m: Matrix, v: Vector) {
    let ret: Vector = [0, 0];
    for (const i of Range) {
        let acc = 0;
        for (const j of Range) {
            acc += v[j] * m[i * 2 + j];
        }
        ret[i] = acc;
    }
    return ret;
}

and, if Vector and Matrix can be aliases to fixed-size typed arrays (see #18471) in addition to tuple, it would be wonderful.

💻 Use Cases

That feature would be very useful in conjunction with noUncheckedIndexedAccess obviously, but also with a way to statically type the length of TypedArray (see #18471) for use in mathematical and graphics code. But even without typed arrays, it would still be useful in day-to-day code. I'm experimenting in switching our 45 kloc Typescript code base to noUncheckedIndexedAccess = true and that feature would increase type safety in several places.

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

Esamina prima gli esempi di indicizzazione delle tuple e le discussioni correlate in #15480 e #18471. Poi traccia il comportamento del controllo dei tipi di TypeScript per gli accessi alle tuple con noUncheckedIndexedAccess e determina come dovrebbero essere validate le espressioni mostrate. Done dovrebbe includere gli esempi motivanti che producono i tipi non-undefined previsti senza modificare il JavaScript emesso.

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.