Last active
December 1, 2015 18:16
-
-
Save jaz303/0bcea983bc8c80a131f3 to your computer and use it in GitHub Desktop.
Is this a bug?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type GeometryUnion = Circle | Rectangle | Polygon | PolyLine; | |
// This does not compile, the error is: | |
// error TS2339: Property 'center' does not exist on type 'Circle | Rectangle | Polygon | PolyLine' | |
class GeometryItem { | |
name: string; | |
object: GeometryUnion; | |
children: GeometryItem[]; | |
constructor(name : string, object : GeometryUnion) { | |
this.name = name; | |
this.object = object; | |
if (this.object instanceof Circle) { | |
console.log(this.object.center); | |
} | |
} | |
} | |
// But if I assign "this.object" to a local and do the type-check on *it*, all is well... | |
class GeometryItem { | |
name: string; | |
object: GeometryUnion; | |
children: GeometryItem[]; | |
constructor(name : string, object : GeometryUnion) { | |
this.name = name; | |
this.object = object; | |
var obj = this.object; | |
if (obj instanceof Circle) { | |
console.log(obj.center); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is by design. Type guards only apply to local variables. I describe some of the reasons here.