'Typescript: how to inference class type that implements an interface
Giving an interface
interface IAnInterface {
}
How to reference and point to a class type that implements that interface!
Meaning! Giving a class:
class AClassThatImplmentsAnInterface implements IAnInterface {
}
How to reference the type that is a class type! Which is the equivalent of:
typeof AClassThatImplementsAnInterface
But at the interface level! Which point to all the classes that implements the interface!
So if i do this:
type IClassTypeMapping = {
[names in SomeLiteralStringUnion]: Class<IAnInterface>
}
Of course Class
doesn't exists in typescript! But i think i explained well what i'm asking about! How to reference the equivalent of Class<IAnInterface>
!?
Is it even possible in Typescript!?
Otherwise if it was just classes! We can use typeof MyClass
!
Also for the above type! If we are creating a mapping object for classes that implements the class! We can always do something like:
export const myMapping = {
Name1: Class1,
Name2: Class2,
// ...
};
// then:
export type MyMappingType = typeof myMapping;
And for the sake of avoiding ambiguity! As i talked much! The question is: How to reference the equivalent of Class<IAnInterface>
? Is it possible in typescript ?
Solution 1:[1]
I'm assuming that you are trying to map to the class itself, not to an instance of the class. So basically something with is constructable. I think this type should work for you:
type Class<I, Args extends any[] = any[]> = new(...args: Args) => I;
We are declaring that Class<IAnInterface>
can be called with the new
keyword and some arguments, and will return an IAnInterface
object (the class instance).
The second argument Args
allows you to define what the constructor arguments are. If there are no arguments it would be an empty array.
declare const MyClass: Class<IAnInterface, []>;
const instance: IAnInterface = new MyClass();
declare const OtherClass: Class<IAnInterface, [number, string]>;
const otherInstance: IAnInterface = new OtherClass(0, "");
Solution 2:[2]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Linda Paiste |
Solution 2 | StPaulis |