非特定属性并在TypeScript中输入?

时间:2015-10-04 10:20:17

标签: typescript

输入

Bundle bundle = getIntent().getExtras();
        String title = bundle.getString("title");

尝试

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

然而,这无法带来代码完成。我想输入interface IObj { [index: string]: IObjVar; } interface IObjVar { car?: number; can(arg: string)?: void; caz?: string[]; } this. / car / can来显示。

2 个答案:

答案 0 :(得分:1)

在修复至少issue #3694之前,您无法提出要求。函数内部this的类型不是类声明的一部分,始终是any。您可以做的最好的事情是将this别名为其他具有正确类型的变量:

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

或者您可以随时明确地投射this

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

答案 1 :(得分:0)

如果你想要有点干(不要自己重复),你可以使用type声明捕获变量的类型。样本:

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;