I am interested in passing "Interfaces" to a function. Not just a specific interface, but any interfaces.
As explained here, for Class, I can handle it as a type.
export type ClassType<T> = { new(...args: any[]): T };
function doSomethingWithAnyClass<T>(anyClass: ClassType<T>) {...}
My question is: Can the same be done for an Interface?
All Classes have constructors and can be called a { new(...args: any[]): T }
type. But what about Interfaces? How can an "Interface" type be represented?
Edit
I am developing a small DI library. When registering a dependency, I provide a pair of a "class"(as token) and a "function that creates an instance of that class"(as factory). These pairs are stored in a map structure. When resolving a dependency, the token is passed to a resolver function.
For instance, let's say there is a class FileLogger
and someone requires an instance of it. To achieve this, I register the dependency by providing a factory () => new FileLogger
with a token FileLogger
. Then, the resolution can be done using
resolve<FileLogger>(FileLogger)
(even though the generic type parameter may seem redundant here).
The issue arises when attempting to use an interface as a token, since it "is not a value". After investigating how other DI libraries tackle this problem, I discovered that tsyringe
simply uses string as a token when working with interfaces.
Currently, I have resorted to converting interfaces into abstract classes. However, I am unsatisfied with this solution and am considering exploring alternative approaches.