Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

133
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda