Skip to content Skip to sidebar Skip to footer

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;
}

class Foo {
    bar: IRectangle & { [key: string]: any; };

    constructor(barInstance:IRectangle){
       this.bar = barInstance;

       this.bar.getArea(); //<-- is code completed because interface IRectangle

       // no type error
       this.bar.someCustomFunction = function() {
       }
    }
}

Solution 2:

Consider a constrained generic type parameter.

interface Base {
  prop: number;
}

interface Child extends Base {
  thing: string;
}

class Foo<T extends Base> {
  bar: T
}

var foo = new Foo<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;
}

class Rectangle implements IRectangle {
    getArea(): void {}
    someCustomFunction(): void {}
}

class Foo<T extends IRectangle> {
    bar: T;

    constructor(barInstance: T){
        this.bar = barInstance;
        this.bar.getArea();

        // no type error
        if (this.bar instanceof Rectangle) {
            (this.bar as any as Rectangle).someCustomFunction = function() {}
        }
    }
}

(code in playground)


Post a Comment for "How To Declare Member Variable As Extended Type In TypeScript?"