Back to questionsWhich type does TypeScript infer for
JuniorTheoryCommon
Which type does TypeScript infer for popped?
class Stack<T> {
private items: T[] = [];
push(item: T): void {
this.items.push(item);
}
pop(): T | undefined {
return this.items.pop();
}
}
const s = new Stack<string>();
s.push("a");
const popped = s.pop();string | undefined
- Expecting plain
stringbecause one item was pushed: tsc does not count pushes, andpop()is declared to returnT | undefined. - Expecting
Tin the result: the type argumentstringfillsTeverywhere in the objects, inpushandpopalike.
- What does tsc report for
s.push(5)? - What type does
new Stack()get without a type argument, and why?