microsoft / microsoft/TypeScript
Using the "in" operator should make bracket access safe on an object
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Go
- Sterne
- 111k
- Forks
- 14.3k
- Ø Merge
- 2 T. 4 Std.
- Gemergte PRs (30 T.)
- 132
Beschreibung
Search Terms
object in keyof bracket operator in
Suggestion
Checking a key with the "in" operator on an object should make it safe to to use in brackets
Use Cases
Useful when writing functions that process input JSON/doesn't have a concrete type.
Examples
// Ideally this uses TypeScripts control flow logic to allow the bracket access.
function getPropFailsToCompile(data: object, key: string): any {
if (!(key in data)) {
throw new Error("Data is malformed")
}
return data[key]
}
// Compiles but keyof object has type 'never' in Typescript
function getPropCompilesButNotReasonable(data: object, key: keyof object): any {
if (!(key in data)) {
throw new Error("Data is malformed")
}
return data[key]
}
// Best way I've gotten this to work.
function getPropWorks(data: object, key: string): any {
if (!(key in data)) {
throw new Error("Data is malformed")
}
return (<any>data)[key]
}
Checklist
My suggestion meets these guidelines:
- [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, etc.)
- [ x] This feature would agree with the rest of TypeScript's Design Goals.
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Beginne mit den drei TypeScript-Beispielen des Issues und der umgebenden Diskussion, um das vorgeschlagene Narrowing-Verhalten für den "in"-Operator und den Zugriff über eckige Klammern zu verstehen. Erledigt ist die Aufgabe, wenn das erste Beispiel ohne Cast typgeprüft wird und dabei das bestehende JavaScript-Laufzeitverhalten erhalten bleibt.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- typescript
- Bereich
- compilers
- Issue-Typ
- Feature
- Schwierigkeit
- 5/5
- Geschätzter Aufwand
- Über eine Woche
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 35/100