microsoft / microsoft/TypeScript
Using the "in" operator should make bracket access safe on an object
Open
Nobody has claimed this yet.
Awaiting More Feedback
Suggestion
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
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.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the issue's three TypeScript examples and the surrounding discussion to understand the proposed narrowing behavior for the "in" operator and bracket access. Done means the first example type-checks without a cast while preserving existing JavaScript runtime behavior.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100