使用ngrx/store遇TS2345错误:MemoizedSelector无法赋值给"isAuthentificated"
解决NgRx Store中TypeScript编译错误TS2345
这个错误的核心原因很明确:你给this.isAuthentificated赋值的是一个NgRx选择器(MemoizedSelector),但isAuthentificated的类型定义却被设置成了字符串"isAuthentificated",TypeScript自然会抛出类型不匹配的错误。
第一步:修正isAuthentificated的类型定义
你需要把isAuthentificated的类型从字符串改为Observable<boolean>,因为store.select()方法返回的是一个Observable流,而不是直接的布尔值或者字符串。
比如,原来错误的定义可能是这样的:
// 错误的类型定义 isAuthentificated: "isAuthentificated";
改成正确的类型(记得导入Observable):
import { Observable } from 'rxjs'; isAuthentificated: Observable<boolean>;
第二步:确认你的选择器定义正确
确保selectAuthentificationStateSelector确实是一个返回布尔值的选择器,比如它的定义应该类似这样:
import { createFeatureSelector, createSelector } from '@ngrx/store'; // 假设你的认证状态接口是这样的 interface AuthState { isAuthenticated: boolean; } // 先获取整个认证feature的状态 const selectAuthState = createFeatureSelector<AuthState>('auth'); // 再创建选择器,提取isAuthenticated字段 export const selectAuthentificationStateSelector = createSelector( selectAuthState, (state: AuthState) => state.isAuthenticated );
第三步:在模板中正确使用(如果需要)
当你在组件模板中使用isAuthentificated时,需要用async管道来订阅这个Observable,因为它是一个流而不是直接的值:
<!-- 模板中的用法 --> <div *ngIf="isAuthentificated | async">用户已登录</div>
这样修改后,TypeScript的编译错误应该就会消失,同时你的NgRx状态订阅逻辑也能正常工作。
内容的提问来源于stack exchange,提问作者Michal Takáč
相关产品推荐
相关产品推荐

