[英]RxJS, Typescript and the dreaded 'Type Mismatch' warning/error
我知道我遗漏了一些明显的东西。 下面是实际在生产中工作的伪代码。 但是,IDE(IntelliJ IDEA)给了我一个我无法破解的错误。 可以使用noinspection TypeScriptValidateTypes
来抑制它,但是,我真正想知道的是发生了什么:
this.authService.onAuthStateChanged()
.pipe(
withLatestFrom(
this.activatedRoute.queryParams.pipe(
map(params => params['returnUrl'])
)
)
)
.subscribe(([authState, returnUrl]) => {
// [...]
});
我在subscribe
线上遇到的错误:
参数类型 ([authState, returnUrl]: readonly [any, any]) => void 不可分配给参数类型 Partial<Observer<[(AuthState | undefined), ...unknown[]]>> | 不明确的
其他相关细节?
// AuthState is just a POJO.
onAuthStateChanged(): BehaviorSubject<AuthState | undefined>
// This is Angular's params object.
// https://angular.io/api/router/Params
export declare type Params = {
[key: string]: any;
};
我正在使用RxJS ~7.5.0
和Typescript ~4.7.4
。 我也在使用Angular ^14.2.0
,尽管这确实不是 Angular 问题。
那么,这里应该发生什么? onAuthStateChanged
发出AuthState
或undefined
取决于用户是否登录。这与一个名为returnUrl
的查询参数相结合,当然它是一个string
。
现在,过去的语法工作方式是使用解构赋值签名([authState, returnUrl])
可以使用两个可观察对象——至少我认为这就是它的名称。 正如我所说,它在现实生活中编译和执行正确,正如其他人在这里所示, StackBlitz上也不会出错(更新以更接近地匹配我的环境与相同tslint
、 angular.json
等)。
然而,我心爱的 IntelliJ...
会不会是我在看最新版 RxJS 的重大变化:
与最新从
- 通用签名已更改。 不要明确传递 generics。
这是伟大的,除了它仍然编译和运行。 所以,有两件事:
如果您将onAuthStateChanged
定义为返回BehaviourSubject
的 function 或直接定义为BehaviourSubject
,则不应出现任何错误。
以下代码不会产生任何类型错误
type AuthState = {};
let onAuthStateChanged = new BehaviorSubject<AuthState | undefined>(null);
let onAuthStateChangedFunc: () => BehaviorSubject<AuthState | undefined>;
// This is Angular's params object.
// https://angular.io/api/router/Params
type Params = {
[key: string]: any;
};
class Foo {
constructor(private activatedRoute: ActivatedRoute) {}
foo() {
onAuthStateChangedFunc() // or
// onAuthStateChanged
.pipe(
withLatestFrom(
this.activatedRoute.queryParams.pipe(
map((params) => params['returnUrl'])
)
)
)
.subscribe(([authState, returnUrl]) => {
// [...]
});
}
}
变量[authState, returnUrl]
分别被正确识别为AuthState
和any
类型。
请参阅此 stackblitz以供参考
该问题在WEB-57220被跟踪,请关注它以获取更新
在设置中启用 Typescript 语言服务 | 语言和框架 | TypeScript应该有助于摆脱错误
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.