microsoft / microsoft/TypeScript

Narrow indexing variable when type-testing indexed access expressions

Open
#45,421 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Awaiting More Feedback Suggestion
Dominant language
Go
Stars
111k
Forks
14.4k
Avg merge
1d 19h
Merged PRs (30d)
117

Description

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'

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the linked Playground and the test function in the issue, reproducing the indexed access errors on TypeScript 4.3.5. Trace how typeof info[k] is inferred inside the loop and conditional branches. Done means the indexed access narrows as expected and the demonstrated string and number assignments no longer produce erroneous never errors.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.