'T' 可以用任意类型实例化,该类型可能不相关

Jua*_*cia 5 generics node.js typescript

我必须对数据结构进行练习,特别是使用双向链表,我不明白为什么当我尝试将两个对象添加到列表中时会出现此错误:

“类型‘{ id_user: number; id_touristic_place: number; review_title: string; review_desc: string; review_points: number; }’类型的参数不可分配给类型‘T’的参数。‘T’可以用任意类型实例化,可能与 '{ id_user: number; id_touristic_place: number; review_title: string; review_desc: string; review_points: number; }'.ts(2345)" 无关

我从 TS 的文档中尝试过这个

public addAtEnd<T>(data: T): void
Run Code Online (Sandbox Code Playgroud)

但这给了我另一个与节点相关的错误

如果您能尝试向我解释错误的原因,我将不胜感激。(我是TS新手)

这是我的代码:

export class Node<T> {
  public data: T;
  public next: Node<T> | null;
  public prev: Node<T> | null;

  constructor(data: T) {
    this.data = data;
    this.next = null;
    this.prev = null;
  }
}

Run Code Online (Sandbox Code Playgroud)
import { Node } from "./Node";
import { ILinkedList } from "./ILinkedList";

export class LinkedList<T> implements ILinkedList<T> {
  private head: Node<T> | null;

  constructor() {
    this.head = null;
  }

  public get gethead(): Node<T> | null {
    return this.head;
  }

  public set sethead(head: Node<T>) {
    this.head = head;
  }

  public addAtEnd(data: T): void {
    const newNode = new Node(data);
    if (!this.head) {
      this.head = newNode;
    } else {
      const getLast = (node: Node<T>): Node<T> => {
        return node.next ? getLast(node.next) : node;
      };

      const lastNode = getLast(this.head);
      newNode.prev = lastNode;
      lastNode.next = newNode;
    }
  }

  public addTwo(): void {
    this.addAtEnd({
      id_user: 1,
      id_touristic_place: 11,
      review_title: "Nice place",
      review_desc: "C:",
      review_points: 0,
    });

    this.addAtEnd({
      id_user: 2,
      id_touristic_place: 11,
      review_title: "Good",
      review_desc: "Not bad at all  ",
      review_points: 0,
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

Nic*_*wer 2

它告诉您,您在这一行传递的对象不可能满足所有可能的类型T

this.addAtEnd({
  id_user: 1,
  id_touristic_place: 11,
  review_title: "Nice place",
  review_desc: "C:",
  review_points: 0,
});
Run Code Online (Sandbox Code Playgroud)

作为无限可能性之一, if Tis number,那么传入 a 才是合法的number(如this.addAtEnd(4)),但您的代码不会传入 a number

泛型的目的是您的代码适用于任何类型,因此您不能对该类型做出任何假设,除非您对其添加限制。对于您的addTwo函数,您将无法创建一个与所有可能的匹配的临时对象T,因此您可以做的唯一实际的事情就是让它接受数据作为参数。这样,任何使用此类的人都可以提供他们想要的类型的数据。

public addTwo(first: T, second: T): void {
  this.addAtEnd(first);
  this.addAtEnd(second);
}
Run Code Online (Sandbox Code Playgroud)