Skip to content

for...in+if...hasOwnProperty is typed differently from Object.keys() #38437

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

Closed
MilesBHuff opened this issue May 9, 2020 · 2 comments
Closed
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug

Comments

@MilesBHuff
Copy link

MilesBHuff commented May 9, 2020

THIS IS NOT THE USUAL Object.keys TYPING "BUG".

TypeScript Version: 3.8.3

Search Terms: Object.keys

Code

function foo<T extends object>(bar: T): void {

    for(const key of Object.keys(bar)) {
        console.log(bar[key]); // TypeError
    }

    for(const key in bar) {
        if(bar.hasOwnProperty(key)) {
            console.log(bar[key]); // No error
        }
    }
}

Issue

The two for-loops above should be functionally identical (with the exception that the second for-loop is less-efficient.) Accordingly, key should have the same type in each.

However, in the former, key is a string, per the logic given by @RyanCavanaugh on Stack Overflow; while, in the latter, key is Extract<keyof T, string>. Correct me if I'm understanding this wrong; but if keyof isn't safe in the former, it seems like it wouldn't be safe in the latter, either.

Related Issues:

#12253, #30314, #13254. #30228, #28899, #28284, #26901, #30749, #31087, #32321, #34498, #35145.

@MilesBHuff MilesBHuff changed the title for..in+if...hasOwnProperty is typed differently from Object.keys() for...in+if...hasOwnProperty is typed differently from Object.keys() May 11, 2020
@RyanCavanaugh RyanCavanaugh added the Working as Intended The behavior described is the intended behavior; this is not a bug label May 11, 2020
@RyanCavanaugh
Copy link
Member

There's actually special treatment to allow this that predates keyof T even existing. This is the intended behavior because for/in is a commonish way to iterate through things like arrays.

@typescript-bot
Copy link
Collaborator

This issue has been marked 'Working as Intended' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug
Projects
None yet
Development

No branches or pull requests

3 participants