class Stack<T> {
private elements: T[] = [];
constructor(private size: number) {
// console.log(this.size);
}
pop(): T {
if (this.elements.length == 0) {
throw new Error('The stack is empty!');
}
return this.elements.pop(); // Type 'T | undefined' is not assignable to type 'T'.
}
}
위 코드에서 pop()
에 나오는데 이유는 함수 리턴하는 시점에서 해당값 타입유추를 하기 때문에 this.elements.length == 0
으로 유추 해버리면 아래 코드처럼 if 다음에 pop을 한번 더 했을 경우에 this.elements.pop()
가 undefined여서 에러가 나옴.
pop(): T {
if (this.elements.length == 0) {
throw new Error('The stack is empty!');
} // 1. compiler가 여기서 아 elements는 안비었구나!라고 생각한다면
this.element.pop() // 2. 근데 element가 한개짜리 array라서 이제 빈 array가 됨.
return this.elements.pop(); // 3. undefined가 됨.
}
이를 해결하려면 처럼 !을 붙여서 undefined
를 가질 수 없게 하거나
return this.elements.pop()!;
이렇게 pop한거를 보고 직접 체크하는게 좋음.
pop(): T {
const lastElement = this.elements.pop();
if (lastElement === undefined) {
throw new Error('The stack is empty!');
}
return lastElement;
}