I want to pass "Interfaces" to a function. Not a specific interface, but any interfaces.
As described 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 I do the same thing for an Interface?
All Classes have constructor and they can be called a { new(...args: any[]): T }
type. Then what about Interface? How do I represent an "Interface" type?
Edit
I'm writing a small DI library. When I register a dependency, I pass a pair of "class"(as token) and a "function that creates an instance of that class"(as factory). The pairs of token and factory are saved in a map structure. When resolving a dependency, I pass the token to a resolver function.
For example, let's say I have a class FileLogger
and someone needs an instance of it. I want to register the dependency and resolve it from wherever it is needed. So I register a factory () => new FileLogger
with a token FileLogger
, and then resolve by resolve<FileLogger>(FileLogger)
(It takes a generic type parameter which is redundant here but I left it to reveal that it does).
The problem is, an interface cannot be used as a token, because it is not a value. I looked for how other DI library solved this problem and found that tsyringe
just uses string as token when dealing with interface.
For now, I ended up changing interfaces into abstract classes. However, I'm not happy with it and about to look for another approach.