0

What is the type of a type ?

This may all sound confusing, so a piece of code may say more than words.

// let's say there is some interface
interface A {
}

// and there is a class that implements it.
// there are a lot of implementations of A.
// but the AImpl is the current/best one.
class AImpl implements A {
}

// and then there is some kind of repository.
// which keeps track of these types, and knows which one is the best.
class Repository {

  // so, this repository returns the most current type.
  static getTypeForA(): Function {
    return AImpl;
  }
}

That's a bit strange, right ? It returns an instance of type Function, while actually it returns a class. It works fine, because a class is a function after all.

But there probably is something better, right? Which type should I use for a type?

bvdb
  • 22,839
  • 10
  • 110
  • 123

1 Answers1

0

You are probably expecting getTypeForA to return an implementation for interface A. so the return type should be the interface A.

interface A {
}

class Impl2 implements A {
}

class Impl1 implements A {
}

class Repository {

  static getImplForA(): A {
    if (condition) {
      return Impl1;
    }

    return Impl2;
  }
}

gilamran
  • 7,090
  • 4
  • 31
  • 50