Microsoft/TypeScript
GitHub ã§èŠãAllow `this` type inside inline object-typed parameters and output
Open
#47,868 opened on 2022幎2æ12æ¥
Experience EnhancementHelp WantedSuggestion
Repository metrics
- Stars
- Â (48,455 stars)
- PR merge metrics
-  (å¹³åããŒãž 6d 17h) (30d ã§ 9 merged PRs)
説æ
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
thistypes. 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:
- 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.
- Other analogous derivatives such as arrays or functions of this are allowed in the same places.