如何缩小别名条件表达式中类的属性类型?
Short:在类方法中,我想进行类型缩小检查,例如this._end === null && this._head === null
,但我想首先将此检查的结果分配给一个变量,然后再在类型缩小中使用它if
条款。它没有按预期工作。
不短: 假设我们有一个Queue class:
class Queue {
private _length: number = 0;
private _head: Node | null = null;
private _end: Node | null = null;
public enqueue(node: Node): boolean {
this._length += 1;
const isQueueEmpty = this._end === null;
if (isQueueEmpty) {
this._head = node;
this._end = node;
return true;
}
this._end.setLink(node); // TypeScript doesn't understand that this._end passed the null check
// in the if statement and writes that this._end can be null.
this._end = node;
return true;
}
}
如果您在以下地方写了一张支票enqueue直接在函数中if条件,那么 TypeScript 就会明白这._结束 is not null:
public enqueue(node: Node): boolean {
this._length += 1;
if (this._end === null) {
this._head = node;
this._end = node;
return true;
}
this._end.setLink(node); // Now TypeScript understand that this._end passed the null check
this._end = node;
return true;
}
但事实证明代码的描述性较差。
而且,总的来说,我需要说的是,该类的两个属性都通过了null查看。具体来说:这个._head and 这._结束.
我写了以下方法:
type QueuePointerKeys = '_head' | '_end';
private _isQueueEmpty(): this is this & { [K in QueuePointerKeys]: null } {
return this._end === null;
}
但这不起作用。如果你把它放在enqueue方法,那么:
public enqueue(node: Node): boolean {
this._length += 1;
if (this._isQueueEmpty()) {
this._head = node; // TypeScript writes that a variable of type null cannot be assigned the type Node
this._end = node; // TypeScript writes that a variable of type null cannot be assigned the type Node
return true;
}
this._end.setLink(node); // TypeScript doesn't understand that this._end passed the null check
// in the if statement and writes that this._end can be null.
this._end = node;
return true;
}
如何使用类方法,例如_isQueueEmpty
用于缩小类型?其工作原理类似于this._end === null && this._head === null
直接用作条件if陈述?