microsoft / microsoft/TypeScript
filter noUncheckedIndexedAccess with own property check
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
ownProperty
hasOwnProperty
noUncheckedIndexedAccess
type check
Suggestion
noUncheckedIndexedAccess is a great feature. However, ts reports that object can be undefined even with hasOwnProperty check.
I suggest that a hasOwnProperty check makes unchecked indexed accesses checked, and return the checked value.
Use Cases
const obj: {[key: string]: string} = {};
// do something with obj
const key = "someKey";
if (Object.prototype.hasOwnProperty.call(obj, key)) {
console.log(obj[key].length); // TS2532: Object is possibly 'undefined'.
}
Since only string values are allowed in obj, the only case such value is undefined is when the key does not exist on obj. The value of obj[key] can only be string. However, typescript still reports type of obj[key] being string | undefined.
Examples
const obj: {[key: string]: string} = {};
// do something with obj
const key = "someKey";
if (Object.prototype.hasOwnProperty.call(obj, key)) {
console.log(obj[key].length); // no problem, since obj[key] has correct type string
}
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
- 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 con il reproducer TypeScript fornito e analizza come il type checker gestisce noUncheckedIndexedAccess e Object.prototype.hasOwnProperty.call. Conferma la diagnostica attuale, quindi determina se l’accesso indicizzato può essere ristretto senza modificare il JavaScript emesso; il lavoro è completo quando l’esempio supera il type check con una copertura di regressione per questo comportamento.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- typescript
- Ambito
- compilers
- Tipo di issue
- Funzionalità
- Difficoltà
- 4/5
- Tempo stimato
- 3-5 giorni
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 35/100