How about the following approach:
interface MyType { doit(): number; } class A implements MyType { public num: number; doit() { return this.num; } } class B extends A { constructor(private times: number) { super(); } doit() { return super.num * this.times; } }
Since the num variable is defined as public, this will work:
var b = new B(4); b.num;
But since it is not defined in the interface, it is:
var b: MyType = new B(4); b.num;
will result in The property 'num' does not exist on value of type 'MyType' .
You can try this in the playground .
You can also wrap it in a module when exporting only the interface, and then from other exported methods you can return instances (factory), so the total amount of variables will be โcontainedโ in the module.
module MyModule { export interface MyType { doit(): number; } class A implements MyType { public num: number; doit() { return this.num; } } class B extends A { constructor(private times: number) { super(); } doit() { return super.num * this.times; } } export function factory(value?: number): MyType { return value != null ? new B(value) : new A(); } } var b: MyModule.MyType = MyModule.factory(4); b.num;
A modified version in this playground .
I know that this is not quite what you requested, but it is pretty close.
Nitzan Tomer Mar 28 '13 at 20:54 2013-03-28 20:54
source share