My reusable service has a public API with documentation and types to make client usage easier.
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;
}
//...
}
In a client implementation:
@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");
//...
}
//...
}
Throughout the evolution of this code, I noticed that TypeScript's autocomplete/intellisense does not suggest methods when using reference variables assigned to method results with defined return types. This is evident in the code where
dataStorageService.getExpirableSecureLocalStorage()
returns a Storable
result stored in the reference variable expirableSecureLocalStorage:any
, making methods like getItem
inaccessible directly within vscode.
How can TypeScript infer the type of a reference variable assigned to a method result with a known return type?
What steps should be taken to enable vscode to suggest available methods for such cases?