为什么 TypeScript 将 Observable<IdentityToken | null> 推断为 Observable<IdentityToken>

问题描述 投票:0回答:1

我正在开发 Angular 服务,其中使用BehaviorSubject 来管理 IdentityToken。 BehaviorSubject 被实例化为

BehaviorSubject<IdentityToken | null>
。然后我通过调用
.asObservable()
从BehaviorSubject 派生一个新的可观察值。然而,当我将鼠标悬停在派生的可观察量上时,Typescript 会将其推断为
BehaviorSubject<IdentityToken>
。好像省略了
null
。根据我的理解,派生的可观察量应该与BehaviorSubject相同。

相关代码:

  private identityToken = new BehaviorSubject<IdentityToken | null>(
    null
  );
  public identityToken$ = this.identityToken.asObservable(); // hovering the `identityToken$` typescript infers is as `BehaviorSubject<IdentityToken>`

完整代码:

import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { StorageKeys } from '../_models/localStorageKeys';
import { map } from 'rxjs/operators';

interface IdentityToken {
  Role: string;
  Permissions: string[];
}

@Injectable({
  providedIn: 'root',
})
export class UserService {
  private identityToken = new BehaviorSubject<IdentityToken | null>(
    null
  );
  public identityToken$ = this.identityToken.asObservable(); // hovering the `identityToken$` typescript infers is as `BehaviorSubject<IdentityToken>`
    
  public isAuthenticated$ = this.identityToken$.pipe(
    map((token) => !!token)
  );

  constructor() {
    this.identityToken = new BehaviorSubject<IdentityToken | null>(
      this.getStoredToken()
    );
  }

  private getStoredToken(): IdentityToken | null {
    const stored = localStorage.getItem(StorageKeys.IDENTITY_TOKEN);
    if (!stored) return null;

    try {
      return JSON.parse(stored);
    } catch (e) {
      localStorage.removeItem(StorageKeys.IDENTITY_TOKEN);
      return null;
    }
  }
}
angular typescript rxjs
1个回答
0
投票

这是由于

strictNullChecks
在您的
false
中为
tsconfig
(或未设置)。

© www.soinside.com 2019 - 2024. All rights reserved.