Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

tsc doesn't recognize coercion of object keys to strings #6267

Closed
cmwilhelm opened this issue Dec 27, 2015 · 1 comment
Closed

tsc doesn't recognize coercion of object keys to strings #6267

cmwilhelm opened this issue Dec 27, 2015 · 1 comment
Labels
Duplicate An existing issue was already created

Comments

@cmwilhelm
Copy link

I ran into a scenario yesterday that surprised me a bit. I was using an object literal to store some unique keys that I later extracted with a for-in loop. The keys were all numbers, but I quickly ran into a problem at runtime because i had forgotten that JavaScript coerces number type keys to strings for objects.

To wit, given the coercion of keys to strings, I was surprised that this type checked:

var ids: Array<number> = [];
const myCollection = {
    0: true,
    1: true
};

for (var key in myCollection) {
    ids.push(key);
}

console.log(ids); // => ["0", "1"]

Is this expected behavior, or should this throw a compile time warning?

(TSC Version 1.7.5)

@vladima vladima added the Duplicate An existing issue was already created label Dec 28, 2015
@vladima
Copy link
Contributor

vladima commented Dec 28, 2015

duplicate of #4518

@vladima vladima closed this as completed Dec 28, 2015
@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

2 participants