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

(TypeScript) How to capture the type provided by the user inside the generic function?

我是 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;
    }

这个函数在包含组件对象列表的游戏对象class中

Component 是一个抽象函数,可以被其他 classes 扩展。我希望此函数 return 用户请求的组件类型。例如这样的事情:

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

我觉得我做错了什么,有什么帮助吗?

您不知道运行时的泛型类型,编译器正在删除所有类型,因为它在 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 {}

如果您将 GameObject class 中的 componentList 成员从(我假设的)常规 Array 替换为 ComponentsArray 那么你的 getComponent 函数很简单:

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

然后:

let gameObject = new GameObject();
let audioComponent = gameObject.getComponent(AudioComponent);