为什么在将 return 类型方法的输出分配给变量时 Typescript 无法推断类型?

Why Typescript can't infer type when you assign a return typed method's output to a variable?

我有一个可重复使用的服务,所以我创建了一个 public API 带有文档和类型以简化客户端的使用。

interface Storable {
  setItem(key: string, value: string): any;
  getItem(key: string): string;
  removeItem(key: string): any;
}

@Injectable({
  providedIn: 'root'
})
export class DataStorageService {
   private expirableSecureLocalStorage:any;
   private secureLocalStorage:any;
   private expirableLocalStorage:any;
   constructor(/*...*/) {
    this.expirableSecureLocalStorage = this.createExpirableStorage(this.createSecureStorage(localStorage));
    this.secureLocalStorage = this.createSecureStorage(localStorage);
    this.expirableLocalStorage = this.createExpirableStorage(localStorage);
   }

   /**
   * Returns a handle to localStorage: Use when you want to compose/decorate storages.
   */
  getLocalStore(): Storable {
    return localStorage;
  }

  /**
   * Returns a handle to sesionStorage: Use when you want to compose/decorate storages.
   */
  getSessionStore(): Storable {
    return sessionStorage;
  }
  /** 
   * Recommended: Singleton - prefer for ordinary operations
   */
  getExpirableSecureLocalStorage(): Storable {
    return this.expirableSecureLocalStorage;
  }

  /** 
   * Recommended: Singleton - prefer for ordinary operations
   */
  getSecureLocalStorage(): Storable {
    return this.secureLocalStorage;
  }

  /** 
   * Recommended: Singleton - prefer for ordinary operations
   */
  getExpirableLocalStorage(): Storable {
    return this.expirableLocalStorage;
  }

  //...

}

然后在客户端中:

@Injectable({
  providedIn: 'root'
})
export class FeatureService {

  expirableSecureLocalStorage:any;

  constructor(private apiService: ApiService, private dataStorageService: DataStorageService) {  
    this.expirableSecureLocalStorage = dataStorageService.getExpirableSecureLocalStorage();                                 
  }
 
  async getFeatures(keyname: string) {
    let features: any;
    let feature: any;
    try {
      let featuresLocalData = this.expirableSecureLocalStorage.getItem("features");
      //...
    }
    //...
   }

当这段代码发展到现在的状态时,我意识到当我将类型Storable添加到DataStorageService时,vscode的autocomplete/intellisense已经开始建议方法。但是,在客户端中,当我将方法的 dataStorageService.getExpirableSecureLocalStorage() 保留为 return 时,Storable 导致引用变量 expirableSecureLocalStorage:any 并且当我尝试使用它的方法时 getItemthis.expirableSecureLocalStorage.getItem("features")一样,vscode不直接提供getItem等两种方法。

为什么 typescript 无法推断分配给具有 return 类型的方法结果的引用变量的类型?

我应该怎么做才能使 vscode 建议可用的方法?

你的代码 expirableSecureLocalStorage:any; 告诉 typescript 无论你在 expirableSecureLocalStorage 中输入什么,它都应该将其处理为“任何东西”,有效地删除它的类型。

您应该导出 Storable 接口并声明 expirableSecureLocalStorage 如下:

expirableSecureLocalStorage: Storable;

Why can't typescript infer the type of the reference variable which is assigned to the result of the method which has a return type?

因为你明确地告诉它通过明确地自己给出类型[=16]来推断类型=].