This is a sample TypeScript generic class, which implements a generic Stack class.
1 | class Stack<T> { |
The code above looks promising, but TypeScript issues an error
1 | Type 'T | undefined' is not assignable to type 'T'. |
Solution
Approach 1. ! operator
If you want to return T you should tell TS to exclude undefined from resulting type by using the ! operator.
1 | class Stack<T> { |
Approach 2. union type
1 | class Stack<T> { |