Microsoft/TypeScript
在 GitHub 查看Allow `this` type inside inline object-typed parameters and output
Open
#47,868 创建于 2022年2月12日
Experience EnhancementHelp WantedSuggestion
仓库指标
- Star
- (48,455 star)
- PR 合并指标
- (平均合并 6天 17小时) (30 天内合并 9 个 PR)
描述
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.