The following example fails to compile (on the last two lines) due to the error shown below.
import { Subject } from 'rxjs';
class Example<T> {
readonly events = new Subject<T>();
constructor(x: T) { }
}
// ...
let example: Example<unknown>;
// ...
example = new Example('some string');
// ...
example = new Example(123);
Error:
Type 'Example<string>' is not assignable to type 'Example<unknown>'.
Types of property 'events' are incompatible.
Type 'Subject<string>' is not assignable to type 'Subject<unknown>'.
Types of property 'observers' are incompatible.
Type 'Observer<string>[]' is not assignable to type 'Observer<unknown>[]'.
Type 'Observer<string>' is not assignable to type 'Observer<unknown>'.
Type 'unknown' is not assignable to type 'string'.ts(2322)
The project where I am seeing this error is using Typescript version 4.3.5 and RxJs version 6.5.5. The error also only happens if the strict flag is enabled in tsconfig.json.
I don't understand why I am seeing this error. Every line in the error message (except for the last line) doesn't feel like an error to me because it's saying that a concrete type is being assigned to an unknown type, which is a valid assignment. For the last line (Type 'unknown' is not assignable to type 'string'
), I understand that assigning unknown
to string
would be an error, but I can't see where such an assignment is happening.
What is the issue with the code example?
Edit
I also noted that the error goes away if I remove the events
property in the Example class.