Skip to content

Instantly share code, notes, and snippets.

@jaz303
Last active December 1, 2015 18:16
Show Gist options
  • Save jaz303/0bcea983bc8c80a131f3 to your computer and use it in GitHub Desktop.
Save jaz303/0bcea983bc8c80a131f3 to your computer and use it in GitHub Desktop.
Is this a bug?
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);
}
}
}
@ahejlsberg
Copy link

This is by design. Type guards only apply to local variables. I describe some of the reasons here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment