Typescript: ES6 getter property does not exist when using union types

Created on 9 Jun 2016  ·  1Comment  ·  Source: microsoft/TypeScript

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'.
Question

Most helpful comment

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;
    }
  }
}

>All comments

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;
    }
  }
}
Was this page helpful?
0 / 5 - 0 ratings