dpoetzsch
dpoetzsch

Reputation: 765

Typescript: this typing in object type

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

class B extends A {}

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

However, type script does not allow the this type in this position. Is there any way to express what I want? Or any reason why it doesn't work?

Upvotes: 1

Views: 278

Answers (1)

Diullei
Diullei

Reputation: 12414

this can't be used in this way. Let me suggest a code to achieve what you want.

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 }

I'd not like to use the anonymous function but this was the way I found to get your result.

You can create a private help function on A to make the code more readable:

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 }

I hope this helps in some way.

Upvotes: 1

Related Questions