Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
aaronlahey opened this issue Oct 2, 2016 · 1 comment
Labels
Fixed A PR has been merged for this issue Suggestion An idea for TypeScript

Comments

@aaronlahey
Copy link

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.

@kitsonk
Copy link
Contributor

kitsonk commented Oct 3, 2016

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

@mhegazy mhegazy added Suggestion An idea for TypeScript In Discussion Not yet reached consensus labels Oct 12, 2016
@mhegazy mhegazy added Fixed A PR has been merged for this issue and removed In Discussion Not yet reached consensus labels Oct 14, 2016
@mhegazy mhegazy added this to the TypeScript 2.1 milestone Oct 14, 2016
@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Fixed A PR has been merged for this issue Suggestion An idea for TypeScript
Projects
None yet
Development

No branches or pull requests

3 participants