0

In Java we can do the following:

Map<Class<?>, Integer> countsByClass;
...
countsByClass.put(String.class, 1);

How to do the same in TypeScript (or something like it)?

let countsByClass: Map<???, Number>;
...
countsByClass.put(???, 1);
Pavel_K
  • 10,748
  • 13
  • 73
  • 186

2 Answers2

3

The following should do it:

class Foo {}

let countsByClass: Map<new (...args: any[]) => any, number> = new Map();
countsByClass.set(Foo, 5);

console.log(countsByClass.get(Foo));

Can also define an intermediate Class type:

type Class<T = any> = new (...args: any[]) => T;

and then the Map declaration becomes cleaner:

let countsByClass: Map<Class, number> = new Map();

Stackblitz demo

Jeto
  • 14,596
  • 2
  • 32
  • 46
  • Check out [this answer](https://stackoverflow.com/a/33224545/4638529) to a similar question for more info on why `new (...args: any[]) => any` works – Wrokar Oct 15 '18 at 22:20
  • Could you explain this `new (...args: any[]) => any`? – Pavel_K Oct 16 '18 at 08:43
  • @Pavel_K Here's a [blog post](https://blog.mariusschulz.com/2017/05/26/typescript-2-2-mixin-classes) explaining it. One interesting part being `The type Constructor is an alias for the construct signature that describes a type which can construct objects of the generic type T and whose constructor function accepts an arbitrary number of parameters of any type.` (`Constructor` is the equivalent of `Class` in my answer.) – Jeto Oct 16 '18 at 10:44
0

I think you mean giving a generic type for a class. Ofcourse you can provide multiple types if you need those.

Example:

class Map<T, U> { }

Correct me if I’m wrong.

Giovanni
  • 400
  • 1
  • 5
  • 22