deno_di
deno_di copied to clipboard
Consider making a Token class for types
Basically just a class to wrap a symbol and a Type so you can get inference through with your types.
e.g.
const token ExampleToken = new Token<IExample>("example") // Internally just has a Symbol("example")
interface IExample {
run(): void;
}
@Service()
class A implements Iexample {
public run(): void {
console.log("A");
}
}
// Service collection setup.
const serviceCollection = new ServiceCollection();
serviceCollection.addTransient(ExampleToken, A); // IExample is inferred as T from Token<T>
const services = serviceCollection.get(ExampleToken); // sevices is inferred as IExample
This is a good idea, but if it's just a type-system trick, then this will work (without needing a wrapper class):
export function sym<T>(desc?: string): ServiceIdent<T> {
return Symbol(desc);
}
It wouldn't require any changes to the rest of the code, since ServiceIdent<T>
is what is used internally to handle the typings of service identifiers anyway.
I'm not 100% on the name, I just picked sym
since it's just a symbol with added type data.