打字稿版本:
每晚(1.9.0-dev.20160217)
代码
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'.
}
}
预期行为:
example.foo
不会在任一方法中引发错误。
实际行为:
example.foo
当example
为Example | Object
抛出:
error TS2339: Property 'foo' does not exist on type 'Example | Object'.
这是 TypeScript 的正常行为,因为它可以保护您免受可能没有.foo
东西的侵害。
如果你想让它工作,你需要将类型缩小到包含.foo
:
class Example {
get foo() {
return true;
}
baz(example: Example) {
example.foo;
}
bar(example: Example | Object) {
if (example instanceof Example) {
example.foo;
}
}
}
最有用的评论
这是 TypeScript 的正常行为,因为它可以保护您免受可能没有
.foo
东西的侵害。如果你想让它工作,你需要将类型缩小到包含
.foo
: