microsoft / microsoft/TypeScript
Narrow object property indexed by another object's property of unique symbol type (like `Symbol.iterator`)
Nessuno ha ancora preso questa issue.
- Lingua principale
- Go
- Stelle
- 111k
- Fork
- 14.3k
- Merge medio
- 2g 4h
- PR unite (30g)
- 132
Descrizione
### 🔍 Search Terms
type guard, narrowing, control flow analysis, property, index, known type, symbol type, bracket notation, unique symbol, known symbol, `Symbol.iterator`, #10530
### ✅ Viability Checklist
- [x] This wouldn't be a breaking change in existing TypeScript/JavaScript code
- [x] This wouldn't change the runtime behavior of existing JavaScript code
- [x] This could be implemented without emitting different JS based on the types of the expressions
- [x] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- [x] This isn't a request to add a new utility type: https://github.com/microsoft/TypeScript/wiki/No-New-Utility-Types
- [x] This feature would agree with the rest of our Design Goals: https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals
### ⭐ Suggestion
This is yet another version of #10530 that doesn't seem to be covered by cases in #56389 or #61176. It *might* even be covered by #62247 and/or #62314 but I'm not sure. TypeScript already narrows by bracket notation when the key is a unique symbol variable:
```ts
declare const s: unique symbol;
declare const x: {}
if ((s in x) && (typeof x[s] === "string")) { x[s].toUpperCase(); }; // okay
```
but this no longer works if the key is a unique symbol property of another object:
```ts
declare const obj: { readonly s: unique symbol }
declare const x: {}
if ((obj.s in x) && (typeof x[obj.s] === "string")) { x[obj.s].toUpperCase(); } // error
```
The suggestion here is to make the latter work like the former.
### 📃 Motivating Example
See https://stackoverflow.com/questions/79877994/why-does-my-test-for-an-iterableiterator-fail
Consider
```ts
function f(x: object) {
if ((Symbol.iterator in x) && (typeof x[Symbol.iterator] === "function")) {
x[Symbol.iterator].length; // error
//~~~~~~~~~~~~~~~~ <-- Object is of type 'unknown'.(2571)
}
}
```
This just looks like a somewhat unfortunate gap in type guarding, where TS knows `Symbol.iterator` is a unique symbol but won't actually do the narrowing unless you put that unique symbol in its own variable directly:
```ts
function f(x: object) {
const symbolIterator: typeof Symbol.iterator = Symbol.iterator;
if ((symbolIterator in x) && (typeof x[symbolIterator] === "function")) {
x[symbolIterator].length; // okay
}
}
```
[Playground link](https://www.typescriptlang.org/play/?target=99#code/CYUwxgNghgTiAEYD2A7AzgF3mgXPArigJYCO+CaAngLYBGSEA3AFCiSwLLpZK0BWeAN7w4UYKgiVseQqXLYa9CPAC+rcNDiJUmeAA8haogDN4ACjNp4RFPoCU8AGSPzGSgAcQSU3oDaaAF14AF5Q+AAiTBgbAHNwuwdhP0CAOgwkAFV3TxgAYSg0EDM7RlVSgHpy+CQAayhKZhNzM14+FKsbeycXMzdPb31fVvag0OCIqNj4xMHh1PSsnPzC4tKVeEr4EBgYJBhmZmNCMAwiVHhjMwNq-nAMROZ4J+tTCwBlRQYUogxtqHSYNZbHoHM5XB4vD5fB86F8fn8AaMwuEjigTmcUNN4IJHs88X4YUpvr8YP89gEUhAQCgYhgABYVKrbXb7PF4yoAPy53J5vI58AAPABaIXwADytxO1isAz6CAA5IQaigkAB3FDylJmABMAFYAOwARjsuKealN2m4ClhEAAkiSyTA8HKBoS4Q6ASF4G6IMSEXsWHimhYqDb7f7AZ0Qd1wf0oaGlOHSYiQsjUejUFicWznslPnaPeTKdTaQyNlVavULWpzUA)
### 💻 Use Cases
1. What do you want to use this for? To allow people to type guard on `Symbol.XXX` properties
2. What shortcomings exist with current approaches? People apparently don't like to copy things to new variables just for narrowing.
3. What workarounds are you using in the meantime? Copy things to new variables. The obvious approach is the old standby, where we replace `if (f(obj[k])) g(obj[k])` with `const objK = obj[k]; if (f(objK)) g(objK)`
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 leggendo l'analisi del flusso di controllo e la gestione dei type guard di TypeScript per la notazione con parentesi quadre, confrontando l'esempio funzionante con una variabile unique-symbol con i casi non funzionanti obj.s e Symbol.iterator. Esamina le issue correlate #10530, #56389, #61176, #62247 e #62314, quindi usa l'esempio Playground fornito per verificare che l'accesso alle proprietà esegua il narrowing in modo coerente quando la modifica sarà completata.
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