Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

134
Vistas
How to declare a Map<T, K> which T should be a variadic class and K should be an instance of T?

I want to declare a Map<T, K> type and the keys in the map is classes and values of the map should be instances of the corresponding key. For example:

class X {}

type InstanceMap = // the type that I want to declare

const map: InstanceMap = new Map();
map.set( X, new X() );
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I don't think this is possible, it would require existentially quantified generic types. You can do

type InstanceMap<T> = Map<{new (): T}, T>

using a constructor type for the key, but this would only allow you to store a specific class (and maybe subclasses?) but not any class. Your code would compile with const map: InstanceMap<X> = new Map();, but map.set(Y, new Y()) would fail.

Instead of trying to instantiate a Map type, we could try to come up with our own interface where the existential quantifier is delegated to the individual methods:

interface InstanceMap {
    set<T>(c: new () => T, i: T): void;
    get<T>(c: new () => T): T | undefined;
}

This works for set and get, but breaks down as soon as you try to declare forEach or iterators.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda