Skip to content

Why doesn't in work as a type guard? #13695

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

Closed
pelotom opened this issue Jan 26, 2017 · 2 comments
Closed

Why doesn't in work as a type guard? #13695

pelotom opened this issue Jan 26, 2017 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@pelotom
Copy link

pelotom commented Jan 26, 2017

Suppose I have a union of two types which are completely distinguishable based on their keys:

type Foo = { x: number } | { y: string }

I'd like to do case analysis on this union in a typesafe way. I would think using in would work, but it doesn't:

function f(foo: Foo) {
  if ('x' in foo) {
    // Type error: Property 'x' does not exist on type '{ y: string; }'
    console.log(foo.x + 5)
  } else {
    // Type error: Property 'y' does not exist on type '{ x: number; }'
    console.log(foo.y.length)
  }
}

However I'm able to define a type guard which does the trick:

export function hasKey<K extends string>(k: K, o: {}): o is { [_ in K]: {} } {
  return typeof o === 'object' && k in o
}

// Now this works:
function f(foo: Foo) {
  if (hasKey('x', foo)) {
    console.log(foo.x + 5)
  } else {
    console.log(foo.y.length)
  }
}

Is there a more correct built-in way to do this that I'm missing? It seems like this is something in should provide out of the bag.

@RyanCavanaugh
Copy link
Member

#10485 ?

@pelotom
Copy link
Author

pelotom commented Jan 26, 2017

Yep, looks like it, thanks.

@pelotom pelotom closed this as completed Jan 26, 2017
@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Jan 26, 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

2 participants