How To Declare Member Variable As Extended Type In Typescript?
Is there a way to define a 'member variable' as an 'extension object' instead of a static type (without using an interface)? Simply something like this pseudocode: class Foo {
Solution 1:
Intersection Types
interface IRectangle {
getArea: () =>number;
}
classFoo {
bar: IRectangle & { [key: string]: any; };
constructor(barInstance:IRectangle){
this.bar = barInstance;
this.bar.getArea(); //<-- is code completed because interface IRectangle// no type errorthis.bar.someCustomFunction = function() {
}
}
}
Solution 2:
Consider a constrained generic type parameter.
interfaceBase {
prop: number;
}
interfaceChildextendsBase {
thing: string;
}
classFoo<T extendsBase> {
bar: T
}
var foo = newFoo<Child>();
foo.bar.thing; // now permitted by the type checker
Solution 3:
I'm not completely sure that I understand you, but if so then something like this:
interface IRectangle {
getArea(): void;
}
classRectangleimplements IRectangle {
getArea(): void {}
someCustomFunction(): void {}
}
classFoo<T extends IRectangle> {
bar: T;
constructor(barInstance: T){
this.bar = barInstance;
this.bar.getArea();
// no type errorif (this.barinstanceofRectangle) {
(this.barasanyasRectangle).someCustomFunction = function() {}
}
}
}
Post a Comment for "How To Declare Member Variable As Extended Type In Typescript?"