Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript never type error during BehaviorSubject instantiation (never[] is not assignable)

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.

like image 319
dhilt Avatar asked Aug 21 '18 11:08

dhilt


1 Answers

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[]

like image 116
Titian Cernicova-Dragomir Avatar answered Sep 22 '22 00:09

Titian Cernicova-Dragomir