Microsoft/TypeScript

Allow `this` type inside inline object-typed parameters and output

Aperta

#47.868 aperta il 12 feb 2022

 (3 commenti) (0 reazioni) (0 assegnatari)TypeScript (13.395 fork)batch import
Experience EnhancementHelp WantedSuggestion

Metriche repository

Star
 (108.860 stelle)
Metriche merge PR
 (Metriche PR in attesa)

Descrizione

Bug Report

🔎 Search Terms

A 'this' type is available only in a non-static member of a class or interface.

🕗 Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about this types. I believe this is a bug (oversight) and not a suggestion because it does already work for what look like very analogous situations.

⏯ Playground Link

Playground link with relevant code

💻 Code

class Foo {
    // Error: A 'this' type is available only in a non-static member of a class or interface.
    badObjWithThisArg(obj: { foo: this }) {}
    badObjWithThisCallback(obj: { foo: (t: this) => this }) {}
    badObjWithThisOutput(): { foo: this } { return { foo: this }; }

    // All fine
    okThisArg(t: this) { }
    okThisCallback(cb: (t: this) => this) {}
    okArrayWithThisArg(a: this[]) { }
    okArrayWithThisCallback(a: ((t: this) => this)[]) { }
    okArrayWithThisOutput(): this[] { return [this]; }
    okIndirectObjWithThisArg(obj: Bar<this>) {}
    okIndirectObjWithThisCallback(obj: Bar<(t: this) => this>) { }
    okIndirectObjWithThisOutput(): Bar<this> { return { foo: this };}
}

interface Bar<T> { 
    foo: T;
}

🙁 Actual behavior

Using { foo: this } as an argument or an output is an error, even in cases where this and other derivatives of this are allowed.

🙂 Expected behavior

Inline object types containing this should be allowed:

  1. Exactly the same type is totally legal as long as it is expressed indirectly through a generic interface instead of inline. There is no actual type difference whatsoever between these situations, as far as I understand.
  2. Other analogous derivatives such as arrays or functions of this are allowed in the same places.

Guida contributor