In my Angular project I'm trying to initialize BehaviorSubject
property with an empty array:
export class Buffer {
$items: BehaviorSubject<Array<Item>>; // or <Item[]>
private _items: Array<Item>; // or Item[]
constructor(settings: Settings) {
this.$items = new BehaviorSubject([]);
}
}
The typescript compiler throws the following error:
error TS2322: Type '
BehaviorSubject<never[]>
' is not assignable to type 'BehaviorSubject<Item[]>
'
I've tried to read about "never" type and I don't understand why I'm getting such an error. Also, if I replace the $items
instantiation with this.$items = new BehaviorSubject(new Array())
there will be no error. But my IDE rightly warns me in that case: "Array instantiation can be simplified".
What is the problem and should I do here? I'm using typescript 2.7.2.
You need to pass on the type parameter explicitly to the constructor
this.$items = new BehaviorSubject<Item[]>([]);
If the compiler has no other information []
will be inferred to never[]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With