打字稿:输入对象类型

时间:2017-04-11 10:44:48

标签: typescript

class A {
    get projections(): { [id: string]: this } { ... }
}

class B extends A {}

new B().projections // should be { [id: string]: B }

但是,类型脚本不允许this类型处于此位置。有没有办法表达我想要的东西?或者它不起作用的任何原因?

1 个答案:

答案 0 :(得分:1)

this不能以这种方式使用。让我建议一个代码来实现你想要的。

class A {
    get projections() { 
        // ...
        let result = {}; // <-- your return object
        return (<T>(obj: T): { [id: string]: T } => result)(this);
    }
}

class B extends A {}

new B().projections // => { [id: string]: B }

我不想使用匿名函数,但这是我找到的结果。

您可以在A上创建私人帮助功能,以使代码更具可读性:

class A {
    private applyResult<T>(obj: T, result: { [id: string]: T }) {
        return result;
    }

    get projections() { 
        // ...
        let result = {}; // <-- your return object
        return this.applyResult(this, result);
    }
}

class B extends A {}

new B().projections // => { [id: string]: B }

我希望这会有所帮助。

相关问题