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

Narrow indexing variable when type-testing indexed access expressions #45421

Open
changwoolab opened this issue Aug 12, 2021 · 2 comments
Open
Labels
Awaiting More Feedback This means we'd like to hear from more people who would be helped by this feature Suggestion An idea for TypeScript

Comments

@changwoolab
Copy link

Bug Report

πŸ”Ž Search Terms

type, inference, object, never

πŸ•— Version & Regression Information

4.3.5

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

interface UserInformationInput {
    userId: string;
    age: number;
}

function test(info: UserInformationInput) {
    console.log("Before info Iteration:", info);
    let k: keyof typeof info;
    for (k in info) {
        if (typeof info[k] === "string") {
            info[k] = "mamamama"; // <-- Error! 
                             // Type 'string' is not assignable to type 'never'.
        }
        else {
            info[k] = 31; // <-- Error!
                        // Type 'number' is not assignable to type 'never'.
        }
    }
    console.log("After info Iteration:", info);
}

test({
    userId: "asdf",
    age: 11
})

πŸ™ Actual behavior

"typeof info[k]" is inferred to be "never"
But at the line 10(if typeof info[k] === "string), "typeof info[k]" was string or number.

Furthermore, after making sure the type of "info[k]" by using "if", it still remains to be "never".

And, although compiler throws an Error above, when I executed the code, it runs very well with the result below
[LOG]: "Before info Iteration:", { "userId": "asdf", "age": 11 }
[LOG]: "After info Iteration:", { "userId": "mamamama", "age": 31 }

πŸ™‚ Expected behavior

I think "typeof info[k]" should be "string | number", not 'never'

@fatcerberus
Copy link

See #30769 for why you’re seeing never rather than string | number.

@RyanCavanaugh RyanCavanaugh added Awaiting More Feedback This means we'd like to hear from more people who would be helped by this feature Suggestion An idea for TypeScript labels Aug 12, 2021
@RyanCavanaugh RyanCavanaugh changed the title Incorrect type inference to Type "never" Narrow indexing variable when type-testing indexed access expressions Aug 12, 2021
@RyanCavanaugh
Copy link
Member

A potential solution would be to narrow k to "userId" (in the truthy case) here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Awaiting More Feedback This means we'd like to hear from more people who would be helped by this feature Suggestion An idea for TypeScript
Projects
None yet
Development

No branches or pull requests

3 participants