How do I get around this "Subject incorrectly extends Observable" error in TypeScript 2.4 and RxJS 5.x?

When I compile, I get the following compiler error in the RxJS declaration files:

node_modules/rxjs/Subject.d.ts(16,22): error TS2415: Class 'Subject<T>' incorrectly extends base class 'Observable<T>'.
  Types of property 'lift' are incompatible.
    Type '<R>(operator: Operator<T, R>) => Observable<T>' is not assignable to type '<R>(operator: Operator<T, R>) => Observable<R>'.
      Type 'Observable<T>' is not assignable to type 'Observable<R>'.
         Type 'T' is not assignable to type 'R'.

What's going on here, and how do I get around this without downgrading to TypeScript 2.3 or earlier?


Solution 1:

Solution

RxJS 5.4.2 should now work perfectly with TypeScript 2.4.1. Simply upgrade to 5.4.2+ if possible.

npm install --save rxjs@^5.4.2

Then try restarting your editor and/or recompile if you don't see an immediate change.

If not, the below solution should work.

Why it's happening

TypeScript 2.4 has a strictness change, and Subject<T> isn't lifting to the correct Observable. The signature really should have been

<R>(operator: Operator<T, R>) => Observable<R>

This will be fixed in RxJS 6.

Alternative Solution

Newer versions of RxJS will have this fixed, but as a temporary workaround, you can use the noStrictGenericChecks compiler option.

In tsconfig.json, put it in "compilerOptions" and set it to true.

{
    "compilerOptions": {
        "noStrictGenericChecks": true
    }
}

On the command line it's --noStrictGenericChecks.

Solution 2:

Today, faced this error and solved this pratically with the below three steps. So sharing the same with the hope, it will help others.

Step 1: In the package.json file change the entry as "rxjs": "5.4.2",

Step 2: Delete the node_modules folder from the project,which is present in the root directory

Step 3 : Now ,Right click the package.json file and click restore like as shown below: enter image description here

Note : It will again create node_module folder with the new files, Now build the solution, hopefully you should not get any build error related to above problem.

Solution 3:

Add

"noStrictGenericChecks": true

in tsconfig.json file

Solution 4:

I have made the below two changes in package.json file.

1) changed the rxjs version to 5.4.1 in dependencies section.

"dependencies": {
"rxjs": "5.4.1" }

2) changed the typescript version to 2.4.0 in devDependencies section.

"devDependencies": { "typescript": "2.4.0" }

I ran 'npm install' command after making the two changes and it worked.

Solution 5:

In your Subject class:

change this line:

lift<R>(operator: Operator<T, R>): Observable<T>;

to :

lift<R>(operator: Operator<T, R>): Observable<R>;