(TypeScript)如何捕获泛型函数内用户提供的类型?

时间:2016-05-14 21:39:22

标签: generics typescript generic-programming

我是TypeScript的新手,这是我写的函数:

/**
     * @function getComponent()
     * @description finds and returns the requested type of component, null if not found
     * @return {any} component
     */
    public getComponent<T extends Component>(): T{
        for(let i = 0; i < this.componentList.length; i++){
            if(<T>this.componentList[i] instanceof Component){
                return this.componentList[i] as T;
            }
        }

        return null;
    }

此函数位于GameObject类中,其中包含Component对象列表

Component是一个抽象函数,可以被其他类扩展。我希望此函数返回用户请求的Component类型。例如:

let gameObject = new GameObject();
let audioComponent = gameObject.getComponent<AudioComponent>(); // no syntax error because AudioComponent extends Component
let myComponent = gameObject.getComponent<foo>(); // syntax error, foo doesn't extend Component

我相信我做错了什么,有什么帮助吗?

1 个答案:

答案 0 :(得分:1)

您在运行时不知道泛型类型,编译器会删除所有类型,因为javascript不支持它。

如果我理解你,那么也许这可以帮到你:

abstract class Component {}

class Component1 extends Component {}
class Component2 extends Component {}
class Component3 extends Component {}

class ComponentsArray extends Array<Component> {
    public getInstanceFor<T extends Component>(componentClass: { new (): T }) {
        for (var i = 0; i < this.length; i++) {
            if ((<any> this[i].constructor).name === (<any> componentClass).name) {
                return this[i];
            }
        }

        return null;
    }
}

let array = new ComponentsArray();
array.push(new Component1());
array.push(new Component2());
array.push(new Component3());

let component2: Component2 = array.getInstanceFor(Component2);
console.log(component2); // Component2 {}

如果您将[{1}}课程中的componentList成员替换为{我认为是的)常规GameObjectArray,那么您的ComponentsArray {1}}功能很简单:

getComponent

然后:

public getComponent<T extends Component>(componentClass: { new (): T }): T {
    return this.componentList.getInstanceFor(componentClass);
}