'Type 'T | undefined' is not assignable to type 'T'. 'T' could be instantiated with an arbitrary type which could be unrelated to 'T | undefined'
WARNING: TypeScript noob question.
I am learning TypeScript via Udemy (https://www.udemy.com/course/typescript-for-professionals). While trying some sample code I get an error in Code:
class Queue4<T> {
private data: Array<T> = [];
push( item: T ):void { this.data.push(item) }
pop( ):T { return this.data.shift() } // error: Type 'T | undefined' is not assignable to type 'T'. 'T' could be instantiated with an arbitrary type which could be unrelated to 'T | undefined'.ts(2322)
}
const myQueue4 = new Queue4<number>();
myQueue4.push( 123 )
myQueue4.push( 234 )
console.log( myQueue4.pop().toPrecision(1) )
Other searches on this error don't help -- samples are too complex. The most useful thing I have come across is this explanation from @jcalz:
Generic functions in TypeScript act as a function representing every possible specification of its generic type parameters, since it's the caller of the function that specifies the type parameter, not the implementer.
'R' could be instantiated with an arbitrary type which could be unrelated to 'Response<Command>'
Even if I remove the code after the class TS still complains. I get the same error for both "target": "es5" and "target": "es2015".
- Why is this happening?
- How do I fix this?
Solution 1:[1]
I had same issue and spent some time on it. This looks related with Linter Checks Strictness. Try:
"noUncheckedIndexedAccess": false,
in your tsconfig.json
It worked with my case.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Seong Marcus |
