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 guard functions do not narrow within switch/case statements #17777

Closed
subvertallchris opened this issue Aug 14, 2017 · 4 comments
Closed
Labels
Duplicate An existing issue was already created

Comments

@subvertallchris
Copy link

TypeScript Version: 2.4.2

Code

interface GeneralInterface {
  value: string;
  foo?: true;
  bar?: true;
}

interface FooInterface {
  value: 'FOO';
  foo: true;
}

function guard<T>(broadObject: any, comparison: string) : broadObject is T {
  return broadObject.value === comparison;
}

function passingTestIf() {
  const broadObject: GeneralInterface = { value: 'FOO', foo: true };
  if (guard<FooInterface>(broadObject, 'FOO')) {
    const narrowed = broadObject;
    return narrowed.value === 'FOO';
  }

  return false;
}

function failingTestCase() {
  const broadObject: GeneralInterface = { value: 'FOO', foo: true };
  switch (true) {
    case (guard<FooInterface>(broadObject, 'FOO')): {
      const notNarrowed = broadObject;
      return notNarrowed.value === 'FOO';
    }
  }

  return false;
}

Expected behavior:

My hope is that the behavior within the body of the case would match the body of if: the const currently defined as notNarrowed should be identified as type FooInterface.

Actual behavior:

Within the body of an if statement, the type guard is evaluated and successfully narrows the object.

image

When evaluated as part of switch/case, the const notNarrowed is still seen as a GeneralInterface, despite being proven to be the more arrow FooInterface.

image

Apologies if I am missing anything, I greatly appreciate your time and work!

@kujon
Copy link
Contributor

kujon commented Aug 14, 2017

See #8934

@subvertallchris
Copy link
Author

Interesting and unfortunate, but thank you for linking me to that. I tried to find something like that but was unable. Is there any chance that this would be considered for resolution now? I'll leave this open for a maintainer to bring the Closehammer down. Thank you!

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Aug 16, 2017
@RyanCavanaugh
Copy link
Member

You can leave a comment in the linked issue. We periodically review them to see if things need to be revisited

@subvertallchris
Copy link
Author

No problem, I'll close this and comment there. Thanks!

@microsoft microsoft locked and limited conversation to collaborators Jun 14, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants