Am1rr3zA
Am1rr3zA

Reputation: 7411

Typescript : Type 'Observable<{}>' is not assignable to type 'Observable'

I have a problem with Observable type, any idea?

import { PostModel } from '../model/postModel';
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';
import * as _ from 'lodash';

class DataStore {

    private posts: PostModel[]  = [];

    private postListSubject = new Subject();

    public postsList$: Observable<PostModel[]> = this.postListSubject.asObservable();

    initializeLessonsList(newPost: PostModel[]) {
        this.posts = _.cloneDeep(newPost);
        this.broadcast();
    }

    addLesson(newPost: PostModel) {
        this.posts.push(_.cloneDeep(newPost));
        this.broadcast();
    }

    broadcast() {
        this.postListSubject.next(_.cloneDeep(this.posts));
    }
}

export const store = new DataStore();

on the line public postsList$: Observable<PostModel[]> = this.postListSubject.asObservable(); I am getting this error

[ts] Type 'Observable<{}>' is not assignable to type 'Observable'. Type '{}' is not assignable to type 'PostModel[]'. Property 'includes' is missing in type '{}'.

Upvotes: 2

Views: 1173

Answers (2)

Elmer
Elmer

Reputation: 9437

this

const s = new Subject();
const o: Observable<Model[]> = s.asObservable();

results in the error you have.

Change it to this

const s = new Subject<Model[]>();
const o: Observable<Model[]> = s.asObservable();

and all is fine!

so...

in your code, change this:

private postListSubject = new Subject();

to this:

private postListSubject = new Subject<PostModel[]>();

If you don't provide a type, the type will default to {}! This is like an object with no properties, and indeed cannot be mapped to the PostModel[] type that you use.

have a nice day!

Upvotes: 0

Robby Cornelissen
Robby Cornelissen

Reputation: 97120

Add type information to your postListSubject declaration to allow the TypeScript compiler to infer the correct type of the Observable that is returned by Subject.asObservable():

private postListSubject = new Subject<PostModel[]>();

Upvotes: 3

Related Questions