我相信这个问题纯粹是 Typescript 相关的,在我的例子中恰好涉及 BehaviorSubject。
我知道这两行:
const myVariable: string | null = 'string';
Run Code Online (Sandbox Code Playgroud)
和
const myVariable: string | null = null;
Run Code Online (Sandbox Code Playgroud)
是有效的语法。因此,我已经声明了这个 BehavoirSubject:
const user: BehaviorSubject<User | null> = new BehaviorSubject(
null
);
Run Code Online (Sandbox Code Playgroud)
这不起作用,因为此错误:
Type 'BehaviorSubject<null>' is not assignable to type 'BehaviorSubject<User | null>'.
Types of property 'observers' are incompatible.
Type 'Observer<null>[]' is not assignable to type 'Observer<User | null>[]'.
Type 'Observer<null>' is not assignable to type 'Observer<User | null>'.
Type 'User | null' is not assignable to type 'null'.
Type …Run Code Online (Sandbox Code Playgroud)