当条件语句使用函数调用的结果而不是布尔表达式时, TS类型推断错误



我有下面的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;
    }
  }
}

现在我想到创建一个辅助函数isEmpty()来检查链表是否为空,如下所示。

  private isEmpty(): boolean {
    return this.head === null || this.tail === null;
  }

然后更改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
    }
  }

但是这会导致一个错误,这是有意义的,因为现在我猜TS不知道我的条件的实现,只有结果,不知道这一点。尾巴或者这个。在else语句中,Head不能再为空。有什么办法可以解决这个问题吗?我能用我的助手而不被tsc抱怨吗?我想过也许使用某种类型的警卫,但想不出什么来。我还是TS的新手,这是可能的,我错过了什么明显我可以做的吗?或者帮手不是一个可行的选择?

您可以使用非空或未定义断言操作符让编译器k现在您知道在该点分配了tail。

this.tail!.nextNode = newNode;
this.tail! = this.tail!.nextNode;

你可以在这里找到更多

最新更新