typescript 语法问题 如何返回 Node 或 Component

public async CreatePrefab<T extends Component | Node>(assetPath: string, parent:Node=null, type=null) : Promise<T> {
    let prefab = await this.AwaitGetAsset(assetPath, Prefab);
    let prefabNode = instantiate(prefab);
    if(parent) {
        parent.addChild(prefabNode);
    }
    if(type) {
        return prefabNode.getComponent(type) || prefabNode.getComponentInChildren(type);
    } else {
        return prefabNode;
    }
}

这样写会报错,不能将Node/Component 分配给T,想要的效果是不传参数 返回Node, 传参数 返回指定的组件, 用any之类的 会导致没有代码提示。

函数重载

async CreatePrefab(path:string): Promise<Node>;
async CreatePrefab<T>(path:string, parent: Node): Promise(T);
async CreatePrefab<T>(path:string, parent:Node):Promise<Node | T> {
 // ....
}

函数重载是一个。还有一个条件类型可以试试看。

另外有一个问题,你 CreatePrefab 方法为社么要写成异步,如果你 addChild 之前父节点销毁了,你也没处理。

还有,如果返回类型不确定,这个 API 绝对是很难用的。

type不传参数就是node,传组件就是具体类型, 我比较喜欢这种写法 :joy:

你要判断你父节点在异步回来的时候 还有效不

谢谢, 看了下官方的getComponent写法也是重载, 我照着抄下

嗯 我补充下

public async CreatePrefab<T extends Component | Node>(assetPath: string, parent:Node=null, type=null) : Promise {

    let prefab = await this.AwaitGetAsset(assetPath, Prefab);

    let prefabNode = instantiate(prefab);

    if(parent) {

        parent.addChild(prefabNode);

    }

    if(type) {

        return prefabNode.getComponent(type) as T || prefabNode.getComponentInChildren(type) as T;

    } else {

        return prefabNode as T;

    }

}

as 一下完事?

试过as, 外面拿不到具体类型, 重载可以

as会被当成Component | Node 不行的