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 inference in switch with user-defined type guards #12491

Closed
goodmind opened this issue Nov 24, 2016 · 1 comment
Closed

Type inference in switch with user-defined type guards #12491

goodmind opened this issue Nov 24, 2016 · 1 comment
Labels
Duplicate An existing issue was already created

Comments

@goodmind
Copy link

TypeScript Version: nightly (2.2.0-dev.20161124)

Code

type UpdateMessage = { message: any }
type UpdateInlineQuery = { inline_query: any }
type UpdateCallbackQuery = { callback_query: any }
type Update = UpdateMessage | UpdateInlineQuery | UpdateCallbackQuery 

function isMessage (x: Update): x is UpdateMessage {
  return (<UpdateMessage> x).message !== undefined;
}

function isInlineQuery (x: Update): x is UpdateInlineQuery {
  return (<UpdateInlineQuery> x).inline_query !== undefined;
}

function isCallbackQuery (x: Update): x is UpdateCallbackQuery {
  return (<UpdateCallbackQuery> x).callback_query !== undefined;
}

function checkType(u: Update) {
  switch (true) {
    case isMessage(u):
      console.log('message', u);
      break;
    case isInlineQuery(u):
      console.log('inline query', u);
      break;
    case isCallbackQuery(u):
      console.log('callback query', u)
      break;
    default:
      console.log('unknown type', u)
  }
}

Expected behavior:

case isMessage(u):
  u.bad_type // Property 'bad_type' does not exist on type 'UpdateMessage'.
  console.log('message', u);
  break;
case isInlineQuery(u):
  u.bad_type // Property 'bad_type' does not exist on type 'UpdateInlineQuery'.
  console.log('inline query', u);
  break;

Actual behavior:

case isMessage(u):
  u.bad_type // Property 'bad_type' does not exist on type 'UpdateMessage'.
  console.log('message', u);
  break;
case isInlineQuery(u):
  u.bad_type // Property 'bad_type' does not exist on type 'UpdateMessage'.
  console.log('inline query', u);
  break;
@RyanCavanaugh
Copy link
Member

Duplicate #8934

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Nov 28, 2016
@mhegazy mhegazy closed this as completed Apr 19, 2017
@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
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants