type assertions example

Topics: General
Oct 8, 2012 at 3:56 PM

i found type assertions hard to understand and wrote some example code. so to rephrase the docs,

var x = <Foo>bar;
doesn't change the type from Bar to Foo, it only exposes the interface of Foo to x..

 

function log(message: string) {
    document.write('<p>');
    document.write(message);
    document.writeln('</p>');
}

class Foo {
    f() : string { return 'foo' }
}

class Bar extends Foo {
    a: string = "i'm a property of Bar";
    f() : string { return 'bar' }
}


var foo = new Foo();
var bar = new Bar();

log(foo.f());
log(bar.f());
log(bar.a);

var x = <Foo>bar;

log(x.f()); // f() from Bar Class
//log(x.a); // doesn't work -> ok

log('x instanceof Foo? ' + (x instanceof Foo));
log('x instanceof Bar? ' + (x instanceof Bar));