I'm doing a game using Phaser with TypeScript. I want to implement a component based architecture for Actors. What I'm trying to achieve is this:
var component:AwesomeComponent = actor.getComponent<AwesomeComponent>();
I know there's a workaround by constructing objects of type T. But I don't like it because I'd probably need to define tons of different constructors to represent all differents kinds of components.
What I'm doing so far is passing a string with the type (of course a number would be better, but I'm still prototyping):
getComponent<T>(componentType:string): T
{
for (let i = 0; i < this.components.length; i++)
{
if (componentType == this.components[i].componentType)
{
return <T><any>this.components[i];
}
}
return undefined;
}
It works, but the result is not good, you have to type the class name twice:
var animComp = actor.getComponent<AnimationComponent>("AnimationComponent");
Any suggestions on how to solve it?
Thank you for your time!