A T
A T

Reputation: 13826

Nonspecific properties and typed this in TypeScript?

Input

const obj = {
    foo: function() {
        this.car = 4;
        this.can("far");
    },
    bar: function() {
        this.caz = ["fa", "ba"];
        this.car = 7;
    }
}

Attempt

interface IObj {
    [index: string]: IObjVar;
}

interface IObjVar {
    car?: number;
    can(arg: string)?: void;
    caz?: string[];
}

However this fails to bring code-completion. I want to type this. and car/can/caz to show up.

Upvotes: 0

Views: 61

Answers (2)

basarat
basarat

Reputation: 275819

If you want to be a bit DRY (don't repeat yourself) you can capture the type of the variable using a type declaration. Sample :

const obj = {
    foo: function() {
        let self: ObjType = this;
        self.car = 4;
        self.can("far");
    },
    bar: function() {
        let self: ObjType = this;
        self.caz = ["fa", "ba"];
        self.car = 7;
    },

    car: 123,
    caz: [],
    can: function(x:string){}
}

type ObjType = typeof obj;

Upvotes: 0

C Snover
C Snover

Reputation: 18766

What you are asking for is not possible until at least issue #3694 is fixed. The type of this inside a function that is not part of a class declaration is always any. The best you could do is to alias this to some other variable with the correct type:

const obj = {
    foo: function() {
        const self: IObjVar = this;
        self.car = 4;
        self.can("far");
    },
    bar: function() {
        const self: IObjVar = this;
        self.caz = ["fa", "ba"];
        self.car = 7;
    }
};

or you could always explicitly cast this:

const obj = {
    foo: function() {
        (<IObjVar> this).car = 4;
        (<IObjVar> this).can("far");
    },
    bar: function() {
        (<IObjVar> this).caz = ["fa", "ba"];
        (<IObjVar> this).car = 7;
    }
};

Upvotes: 1

Related Questions