Home > Mobile >  Is there anything in TypeScript similar to Class<T> in Java, to extract the type of a class co
Is there anything in TypeScript similar to Class<T> in Java, to extract the type of a class co

Time:12-09

I need such a feature like Class in Java for TypeScript, but I haven't been able to find it.

Class<T> is what I'm looking for. I think it could be NewableFunction<T>. But there is no such thing. I can't use Map<A, InstanceType<A>>, obviously it's not correct.

The "setIt" method and "the left end of this Map" to passing only the type of class A and subclasses of class A, not its instances or a class that are not subclasses of A.

I know that Typescript compiles to Javascript with type erasure just like Java does.


class Foo {
  public static readonly bar : Map<Class<A>, A>;

  public static declare getIt(clazz: Class<A>) : A;

  public static setIt(clazz: Class<A>) : A {
    const a = new clazz();
    this.bar.set(clazz, a);
    return a;
  }
}

declare class A;
declare class B extends A;

The left side of the dictionary is its class, and the right side is the object of the corresponding class.


And the declaration of covariant and contravariant classes?
Such as "in" and "out" key words of kotlin.
I'm looking for that too.


class Foo{
  public map: Map<Class<in A>, A>
  public setIt(clazz: Class<in A>): A;
}

I searched for it and also looked at the official documentation, including the type declaration for stdlib. But I didn't get any results.

CodePudding user response:

About your first question, yes. If you define a class with

class A {}

then you have two things : the actual A, which is a constructor (a kind of function), and the type A, which types instances of A.

But you can get the type of the constructor (the actual thing stored in A) with typeof A.

In you example, translating to TypeScript, you'd get :

const foo = {
  bar : new Map<typeof A, A>(),

  getIt(clazz: typeof A) : A | undefined {
    return this.bar.get(clazz)
  },

  setIt(clazz: typeof A) : A {
    const a = new clazz()
    this.bar.set(clazz, a)
    return a
  }
}

I translated your class Foo to a basic object because it had only static properties, which in TypeScript makes no sense as a class.

  • Related