Skip to content

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

Open
@changwoolab

Description

@changwoolab

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'

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