I want to specify the type of values for every key in Map. I mean that one specific key has to have a value with a specific type.
With using an object everything works fine:
import { Logger } from './services/logger';
import { HTTP } from './services/http';
class Container<T> {
private services: T;
constructor() {
this.services = {} as T;
}
register<K extends keyof T>(name: K, service: T[K]) {
this.services[name] = service;
}
}
type Services = {
logger: typeof Logger,
http: typeof HTTP,
}
const container = new Container<Services>();
container.register('logger', Logger);
if I try to set another type:
container.register('logger', HTTP);
I got an error: Argument of type 'typeof HTTP' is not assignable to parameter of type 'typeof Logger'.
So it works as I expected.
Now, I'm trying to do the same with Map:
class Container<T> {
private services: T;
constructor() {
this.services = Map as T;
}
register<K extends keyof T>(name: K, service: T[K]) {
this.services.set(name, service);
}
}
type Services = {
logger: typeof Logger,
http: typeof HTTP,
}
const container = new Container<Services>();
but I have not succeeded.
Can I do it with Map? I would appreciate any help.