-
Notifications
You must be signed in to change notification settings - Fork 12.9k
Open
Labels
Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScriptAn idea for TypeScript
Description
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.
jaydenseric, Stophface, alker0 and mjy9088vatosarmat, bradyasana, blt-r and joealden
Metadata
Metadata
Assignees
Labels
Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScriptAn idea for TypeScript