Skip to content

Type narrowing of string literal seems to get loosened in callbacks #14748

Description

@Rycochet

TypeScript Version: 2.2.1

Code

function myValueArg(arg: "value") { }

function myStringArg(arg: string) { }

namespace ns { // Not needed, but shows it's not scope related
    let str = "value";

    if (str === "value") {
        myValueArg(str);
        [].forEach(() => {
            myValueArg(str); // Argument of type 'string' is not assignable to parameter of type '"value"'.
        });
    } else {
        myStringArg(str);
        [].forEach(() => {
            myStringArg(str);
        });
    }
}

Expected behavior:
No warnings: the value (and type) of str has not changed.

Actual behavior:
Warning Argument of type 'string' is not assignable to parameter of type '"value"'.

Activity

  1. gcnew commented on Mar 21, 2017

    @gcnew
    Contributor

    Use const. let bindings are reset because the function might be invoked asynchronously and a new value could be set to the let variable in the mean time.

  2. Rycochet commented on Mar 21, 2017

    @Rycochet
    Author

    That sort of makes sense (though this is just a sample, the real code I noticed it on is most definitely not a constant). Wouldn't it be better to annotate things that are definitely not asynchronous to prevent this spurious warning?

  3. ghost removed
    Needs InvestigationThis issue needs a team member to investigate its status.
    on Nov 2, 2017
  4. ghost added
    DuplicateAn existing issue was already created
    on Nov 2, 2017
  5. typescript-bot commented on Nov 16, 2017

    @typescript-bot
    Contributor

    Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

  6. locked and limited conversation to collaborators on Jun 21, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions