microsoft / microsoft/TypeScript
Destructuring object with generic key should reject undefined
Nessuno ha ancora preso questa issue.
- Lingua principale
- Go
- Stelle
- 111k
- Fork
- 14.3k
- Merge medio
- 1g 19h
- PR unite (30g)
- 117
Descrizione
🔎 Search Terms
destructure, generic key, undefined
🕗 Version & Regression Information
This is the behavior in every version I tried (back to at least 5.0), and I reviewed the FAQ for entries about destructuring
⏯ Playground Link
💻 Code
interface T { a?: unknown; b?: unknown; c?: unknown }
function f<L extends keyof T>(k: L, t: T | undefined): unknown {
const { [k]: v } = t // should error (crashes if t undefined)
const _v2 = t[k] // equivalent code, does error
return v
}
🙁 Actual behavior
TS does not error on the destructuring, even though it will crash at runtime if t is undefined, and it errors on equivalent code using object-access syntax.
🙂 Expected behavior
TS should error on the indicated line.
Additional information about the issue
This is simplified from an actual example in our codebase. Obviously in this case it's silly to destructure but this was part of a larger block of destructuring so the code would at a glance seem reasonable.
Note that the destructured value does end up having a funky type (T | undefined)[L], which presumably it's hard to do anything with. But of course it's still assignable to unknown, and thus usable in various ways. (In the actual code in question, the authors were doing other complicated things, running an issue similar to #40312, and ended up casting through unknown to the type they wanted.)
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Inizia dall’esempio Playground collegato e confronta la gestione da parte del checker della destrutturazione di proprietà calcolate con l’espressione equivalente di accesso indicizzato. Segui la chiave generica e l’oggetto potenzialmente non definito durante il controllo dei tipi; il lavoro è completato quando la riga di destrutturazione riceve un errore appropriato senza regressioni per la destrutturazione valida.
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
- 38/100