首页 > 解决方案 > 如何使用接口映射来创建新类型?

问题描述

在 Typescript 中这样的事情可能吗?

const enum ET {
  Collision,
  Dying,
  Collected
}

interface EventMap {
  [ET.Collision]: CollisionEvent;
  [ET.Dying]: DyingEvent;
  [ET.Collected]: CollectedEvent;
}

class GameEvent {
  static grabFromPool(type: ET) {
    let entry = GameEvent.pool[type];

    if (entry.length === 0) {
      return new EventMap[type](); // this line is throwing the error
    } else {
      return entry.pop();
    }
  }

  private static pool: Array<Array<GameEvent>> = [ [], [], [] ];
}

我正在尝试创建一个对象池。我标记的行给出了以下错误:

'EventMap' only refers to a type, but is being used as a value here.ts(2693)

我正在尝试CollisionEvent根据给定的类型参数(ET)实例化相应的类(例如:)。

标签: typescriptpool

解决方案


在您的代码中,EventMap只是一个类型,没有运行时值。你需要一个真实的对象:

const EventMap = {
  [ET.Collision]: CollisionEvent,
  [ET.Dying]: DyingEvent,
  [ET.Collected]: CollectedEvent,
}

如果您需要类型:

type EventMap = typeof EventMap
// Inferred as this \/
{
    0: typeof CollisionEvent;
    1: typeof DyingEvent;
    2: typeof CollectedEvent;
}

请注意,在类型表达式中,CollisionEvent指的是类的实例,并且typeof CollisionEvent指的是类及其构造函数。


推荐阅读