0

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.

Nazar
  • 172
  • 1
  • 1
  • 8
  • See the other question and answer for how to do this. I don't really understand *why* you would want this, though. Is there something `Map` does for you that a plain object does not? – jcalz Aug 03 '22 at 16:28
  • @jcalz honestly, I like to use Map methods such as 'get', 'set', and especially 'has' method to check if a key already exists. Anyway, thanks for the reply. – Nazar Aug 03 '22 at 19:13

0 Answers0