【发布时间】:2021-10-26 04:02:03
【问题描述】:
我必须对数据结构进行练习,特别是使用双向链表,但我不明白为什么当我尝试将两个对象添加到列表时出现此错误:
“'{ id_user: number; id_touristic_place: number; review_title: string; review_desc: string; review_points: number; }'类型的参数不能分配给'T'类型的参数。 'T' 可以用与 '{ id_user: number; 无关的任意类型实例化。 id_touristic_place:号码;评论标题:字符串; review_desc:字符串; review_points:数字; }'.ts(2345)"
我从 TS 的文档中试过这个
public addAtEnd<T>(data: T): void
但这给了我另一个与节点相关的错误
如果您能尝试向我解释错误的原因,我将不胜感激。 (我是 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;
}
}
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,
});
}
}
【问题讨论】:
标签: node.js typescript generics