Skip to content

Suggestion: Allow forcing only square bracket navigation on a given object #20240

Closed

Description

Hi,

I have a situation that keeps coming up. It leads to avoidable bugs, and I want to know if there is way to prevent it.

Let's say I am building a lookup object, where each key is a person's id and each value is a person object. I am building this object dynamically from an array of objects which are only known at runtime.

var peopleArray = [  // Only known at runtime
    { id: "1", name: "Tim" },
    { id: "2", name: "Tom" },
    { id: "3", name: "Ted" }
];

var people: { [id: string]: any } = {};
peopleArray.forEach(person => {
    people[person.id] = person;
});

Now sometimes when not thinking, or as a result of a big refactor, I find myself accessing objects on the object with dot syntax, thinking it is another object of another type, like this...

var aThing = people.something;

something will never be a key in this object because it is only keyed by ids, but TypeScript will accept this as valid code and not raise an error because the object could be keyed by any string.

The assertion I can make here is that this object should only be accessed with square bracket syntax, not dot-syntax since it is impossible to know the values at compile time.

So, to prevent this happening, is there (or could there be) a way of the compiler raising errors for dot-syntax navigation on an object, if the programmer knows that the keys will only be known at runtime?

Something like:

var people: { indexable [id: string]: any } = {};
var aThing = people.something; // Raises an error
var aThing2 = people['something']; // Doesn't raise an error

Hope this makes sense.

Thanks in advance!
Chris

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions