microsoft / microsoft/TypeScript

Type guard cannot remove `undefined` from `Partial<T>[keyof T] | undefined`

Aperta
#45,257 4 commenti 2 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

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

Descrizione

Bug Report

When writing a function to merge object A with non-undefined values from object B into C where A is of type T and B is of type Partial<T>, I came across a situation where the type guard seems to be failing.

🔎 Search Terms
  • type guard
  • Partial
🕗 Version & Regression Information
  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about common-bugs-that-arent-bugs
⏯ Playground Link

Playground link with relevant code

💻 Code
function merge<T>(a: T, b: Partial<T>, keys: (keyof T)[]): T {
    const v: T = { ...a };
    for (const key of keys) {
        const value = b[key];
        if (value !== undefined) {
            v[key] = value;
        }
    }
    return v;
}
🙁 Actual behavior

There is an error at v[key] = value;:

Type 'T[keyof T] | undefined' is not assignable to type 'T[keyof T]'.
  Type 'undefined' is not assignable to type 'T[keyof T]'.

image

Clearly value is NOT undefined, yet the compiler complains that it is.

🙂 Expected behavior

I would expect that the code compiled.

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 il TypeScript Playground collegato e riproduci l’errore nella funzione generica merge in v[key] = value dopo il controllo value !== undefined. Traccia il comportamento del checker per Partial[keyof T] e l’assegnazione indicizzata; il lavoro è completato quando l’esempio viene compilato senza indebolire il type checking previsto.

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

Valutazione

Stack tecnologico
typescript
Ambito
compilers
Tipo di issue
Bug
Difficoltà
4/5
Tempo stimato
3-5 giorni
Stato di attività
Ferma
Chiarezza
Specificata chiaramente
Idoneità per principianti
45/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.