user5182503
user5182503

Reputation:

Class in generic and as literal in TypeScript

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);

Upvotes: 0

Views: 48

Answers (2)

Jeto
Jeto

Reputation: 14927

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

Upvotes: 2

Giovanni
Giovanni

Reputation: 425

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.

Upvotes: 0

Related Questions