Skip to content

Using the "in" operator should make bracket access safe on an object #34867

@kwasimensah

Description

@kwasimensah

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions