1 回答
TA贡献1804条经验 获得超2个赞
您将 next 定义为 getter,因此必须像这样访问它:this.top = this.top?.next
甚至编译的唯一原因const value = this.top?.value();是因为您使用“任何”(不要这样做,永远!!),并且打字稿假定这get value可能会返回您正在调用的函数。
您应该使用泛型定义 StackNode。例如,
class StackNode<T> {
private val: T;
private nxt: StackNode<T> | undefined = undefined;
constructor(val: T, nxt?: StackNode<T> | undefined) {
this.val = val;
this.nxt = nxt || undefined;
}
get value(): T {
return this.value;
}
get next(): StackNode<T> {
return this.next;
}
}
class Stack<T> {
private capacity!: number;
private top?: StackNode<T> | undefined = undefined;
private size: number = 0;
constructor(capacity: number, initialValues?: Array<any>) {
this.capacity = capacity;
if (initialValues) {
this.size = initialValues.length;
this.top = this._initStack(initialValues, initialValues.length - 1);
}
};
private _initStack = (array: Array<any>, idx: number): StackNode<T> => {
if (idx == 0) {
return new StackNode(array[idx], undefined);
} else {
return new StackNode(array[idx], this._initStack(array, idx-1));
}
}
pop(): T | undefined {
const value = this.top?.value(); //doesn't compile
this.top = this.top?.next(); //doesn't compile either
return value;
}
}
然后,const value = this.top?.value();也不会编译。
添加回答
举报
