Microsoft/TypeScript

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

Open

#47.868 aberto em 12 de fev. de 2022

Ver no GitHub
 (3 comments) (0 reactions) (0 assignees)TypeScript (6.726 forks)batch import
Experience EnhancementHelp WantedSuggestion

Métricas do repositório

Stars
 (48.455 stars)
Métricas de merge de PR
 (Mesclagem média 6d 17h) (9 fundiu PRs em 30d)

Description

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.

Guia do colaborador