Bug报告
在构造函数中使用空值合并来初始化一个没有类型注解的类成员将导致TS7022错误。
🔎 搜索词
nullish
, coalescing
, 7022
, ??
, 和 ts7022
🕗 版本与回归信息
- 我尝试了每个版本,发现这种行为都存在,我也查阅了关于空值合并和类型推断的FAQ条目。
⏯ Playground链接
带有相关代码的Playground链接
💻 代码
export class Node {
#parent
#children = new Children(this)
constructor (parent?: Node | null | undefined) {
// Remove `??` and the code after and the code compiled. Now #parent is undefined which is not desired.
this.#parent = parent ?? null
}
get parent () { return this.#parent }
get children () { return this.#children }
}
export class Children {
#parent
#head
#tail
constructor (parent: Node) {
this.#parent = parent
this.#head = new Node(parent)
this.#tail = new Node(parent)
}
}
🙁 实际行为
尝试编译示例代码会导致TS7022错误: '#parent' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.
🙂 预期行为
代码应该能够编译,并且 #parent
应该被类型化为 Node
| null
。
1条答案
按热度按时间ghg1uchk1#
这是一个与我在这里诊断的问题非常相似的问题(我们在这里的代码路径几乎完全相同,只是问题的起源略有不同)
问题在于,这个初始化器中的二元表达式在这里创建了一个联合类型(左类型和右类型的联合),而这个联合是子类型约简的主题。这反过来要求
parent
的属性,并遇到了一个循环。这个特定的例子可能可以避免,因为右边的类型是
null
,左边的类型不是空值,但其他提到的问题表明还有其他类似的情况,这些情况都无法帮助我们。希望有一个更智能的修复方法,但我没有想法。