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'.
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;
}
}
}
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
: