Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

139
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!