[英]TS Error with Type Inference within Conditional Statement, when the condtional is using the result of a function call instead of a boolean expression
I have the following TypeScript class for a Linked List class, and everything works fine.我有以下用于链接列表类的 TypeScript 类,并且一切正常。
type ListItem = number | string | object;
class Node {
private value: ListItem;
private next: Node | null;
constructor(value: ListItem) {
this.value = value;
this.next = null;
}
set nodeValue(value: ListItem) {
this.value = value;
}
set nextNode(next: Node | null) {
this.next = next;
}
get nodeValue(): ListItem {
return this.value;
}
get nextNode(): Node | null {
return this.next;
}
}
export class LinkedList {
private head: Node | null;
private tail: Node | null;
constructor(value: ListItem | null = null) {
// Case 1: Linked List is initialised with 1 argument
// Case 2: Linked List is initialised with null
if (value) {
const node = new Node(value);
this.head = node;
this.tail = node;
} else {
this.head = null;
this.tail = null;
}
}
public addLast(item: ListItem): void {
const newNode = new Node(item);
// Case 1 (if): Empty List
// Case 2 (else): Non Empty List
if (this.head === null || this.tail == null) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail.nextNode = newNode;
this.tail = this.tail.nextNode;
}
}
public addFirst(item: ListItem): void {
const newNode = new Node(item);
// Case 1 (if): Empty List
// Case 2 (else): Non Empty List
if (this.head === null || this.tail === null) {
this.head = newNode;
this.tail = newNode;
} else {
newNode.nextNode = this.head;
this.head = newNode;
}
}
}
Now I thought of creating a helper function, isEmpty(), to check if the Linked List is empty as shown below.现在我想创建一个辅助函数 isEmpty() 来检查链表是否为空,如下所示。
private isEmpty(): boolean {
return this.head === null || this.tail === null;
}
And then changing the addLast() function as follows然后改变 addLast() 函数如下
public addLast(item: ListItem): void {
const newNode = new Node(item);
// Case 1 (if): Empty List
// Case 2 (else): Non Empty List
if (this.isEmpty()) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail.nextNode = newNode; // error
this.tail = this.tail.nextNode; // error
}
}
But this causes an error, which makes sense because now I guess TS is not aware of the implementation of my conditional, only the result and does not know this.tail or this.head can no longer be null inside the else statement.但这会导致错误,这是有道理的,因为现在我猜 TS 不知道我的条件的实现,只知道结果并且不知道 this.tail 或 this.head 在 else 语句中不能再为空。 Is there any way around this.
有没有办法解决。 Could I somehow use my helper without the tsc complaining.
我可以在没有 tsc 抱怨的情况下以某种方式使用我的助手吗? I thought of perhaps using a type guard of some sort but couldn't think of something.
我想过也许使用某种类型的防护,但想不出什么。 I am still new to TS, is this possible, am I missing something obvious I could do?
我还是 TS 新手,这可能吗,我是否遗漏了一些我可以做的明显事情? Or is the helper not a feasible option?
或者帮手不是一个可行的选择?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.