I lose typing when I use Angular's dependency injection. I don't know why? Can someone explain and find a solution to use DI while having strict typing? I'm using a service to strictly type local storage, here's some context:
I use a class with a generic type.
@Injectable()
export class LocalStorageService<T> implements iStorageService<T> {
// ...
constructor(@Inject(LOCAL_STORAGE_NAMESPACE) private namespace: string) {}
set<K extends keyof T>(key: K, value: T[K]) {
if (this.storage) {
this.storage.setItem(
this.namespace + key.toString(),
JSON.stringify(value)
);
}
}
// ...
}
and at consumer level :
providers: [
{
provide: LOCAL_STORAGE_NAMESPACE,
useValue: 'dumbnamespace',
},
LocalStorageService<LocalStorageModel>,
],
I tried too :
providers: [
{
provide: 'LocalStorageService',
useFactory: () => new LocalStorageService<LocalStorageModel>('namespace'),
},
],
with LocalStorageModel :
interface LocalStorageModel {
[LocalStorageKey.Name]: string;
}
And in the component :
private testTypeChecking = inject(LocalStorageService).set(LocalStorageKey.City, 22);
No error here when it should be :(
Doing it this way works (we have an error, number is not a string), but without using Angular's DI.
const testTypeChecking = () => {
const localStorageService = new LocalStorageService<LocalStorageModel>('id');
localStorageService.set(LocalStorageKey.Name, 22);
};
Does anyone have an explanation?
It's because the generic parameter isn't specified so this is expected