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

ES6 getter property does not exist when using union types #9050

Closed
bradleyayers opened this issue Jun 9, 2016 · 1 comment
Closed

ES6 getter property does not exist when using union types #9050

bradleyayers opened this issue Jun 9, 2016 · 1 comment
Labels
Question An issue which isn't directly actionable in code

Comments

@bradleyayers
Copy link

TypeScript Version:

nightly (1.9.0-dev.20160217)

Code

class Example {
  get foo() {
    return true;
  }

  baz(example: Example) {
    example.foo;
  }

  bar(example: Example | Object) {
    example.foo; // error TS2339: Property 'foo' does not exist on type 'Example | Object'.
  }
}

Expected behavior:

example.foo would not throw an error in either method.

Actual behavior:

example.foo when example is Example | Object throws:

error TS2339: Property 'foo' does not exist on type 'Example | Object'.
@kitsonk
Copy link
Contributor

kitsonk commented Jun 9, 2016

That is the normal behaviour of TypeScript as it is guarding you against something that might not have a .foo.

If you want this to work, you need to narrow the type down to something that contains .foo:

class Example {
  get foo() {
    return true;
  }

  baz(example: Example) {
    example.foo;
  }

  bar(example: Example | Object) {
    if (example instanceof Example) {
      example.foo;
    }
  }
}

@mhegazy mhegazy added the Question An issue which isn't directly actionable in code label Jun 9, 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
Question An issue which isn't directly actionable in code
Projects
None yet
Development

No branches or pull requests

3 participants