Skip to content

Type string does not narrow when checked for equality with a string literal. #11306

Description

TypeScript Version: 2.1.0-dev.20160918

Code

export function returnAnyString(): string {
  return "";
}

export function acceptsOnlyFoo(value: "foo"): void {
  // ...
}

const value = returnAnyString();

if(value === "foo")
  acceptsOnlyFoo(value); // error TS2345: Argument of type 'string' is not assignable to parameter of type '"foo"'.

Expected behavior:

The === to narrow type string to a string literal type when checking for equality with a string literal. I would expect the above example to be the same as the following example which does work...

export function returnAnyString(): string {
  return "";
}

export function acceptsOnlyFoo(value: "foo"): void {
  // ...
}

function isFoo(s: string): s is "foo" {
  return s === "foo";
}

const value = returnAnyString();

if(isFoo(value))
  acceptsOnlyFoo(value);

Actual behavior:

The type is still string.

Activity

  1. kitsonk commented on Oct 3, 2016

    @kitsonk
    Contributor

    Essential a dupe of #7447 which was supposed to be implemented in #9407 but doesn't appear to be working.

  2. added
    FixedA PR has been merged for this issue
    and removed on Oct 14, 2016
  3. locked and limited conversation to collaborators on Jun 19, 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

    FixedA PR has been merged for this issueSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions