Skip to content

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

Closed
@aaronlahey

Description

@aaronlahey

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.

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