微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何从泛型 Typescript 函数返回具体类型?

如何解决如何从泛型 Typescript 函数返回具体类型?

我正在开发一个实体组件系统,并希望能够从我的 get 函数返回具体类型。这是我目前的做法,它有效,但没有任何类型信息:

enum CT { Null,Input,Transform,Physics } // CT = Component Type

class Component {
  type: CT;

  constructor(type: CT) { this.type = type; }
}

class PhysicsComponent extends Component {
  veLocity: Vec2;
  
  constructor() { 
    super(CT.Physics); 

    this.veLocity = new Vec2(0,0);
  }
}

class Entity {
   components: Map<CT,Component>;

   get = (componentType: CT): any => {
     return this.components.get(componentType);
   }
}

let physics = entity.get(CT.Physics); // no type-safety since return type is any

我希望类型安全和代码完成,所以我更愿意在客户端代码中做这样的事情:

let physics = entity.get<PhysicsComponent>();

但我不确定如何设置库代码以允许类似的事情。例如,components 会是什么,我的 get 函数会是什么样子?有点像..

components: Map<typeof Component,Component>;

get<T extends Component>(): T {
  return this.components.get(typeof T) as T;
}

?但这当然不能编译。

此外,我还担心性能。目前 CT 枚举只是数字,所以一切都非常快(它必须如此,因为查询是游戏中最常见的操作),我的直觉是所有这些 typeof 调用,转换和获取类型信息(AFAIK 只是在整个类上调用 toString)是非常缓慢的操作,因此我什至不确定这是否是一个好主意,尽管符合人体工程学,但由于性能成本。有什么建议吗?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。