1
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?

1
  • 1
    this refers to a specific instance of an object, not a class itself. That's why it doesn't work. Commented Apr 11, 2017 at 12:10

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Nice answer. Funnily the vscode editor now infers exactly my suggested type annotation when I hover over the definition of projections. So is it really true that projections now has a type that is simply not expressible using an explicit type annotation? I somehow feel this is a flaw in the language then as I'm writing a type definition where I have to make the type explicit.
That is the unique way I found to do it. You can use the command tsc your_file.ts -d to use the typescript compiler to extract the definition from this code. Unfortunately you will see a signature like: ... { [id: string]: this; } that not works. Maybe you can do it in another way using generics.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.