如何使用接口映射来创建新类型?
How to use an interface mapping to create a new type?
在 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)
我正在尝试根据给定的类型参数 (ET
) 实例化相应的 class(示例:CollisionEvent
)。
在您的代码中,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;
}
请注意,在 type 表达式中,CollisionEvent
指的是 class 的实例,而 typeof CollisionEvent
指的是 class 及其构造函数。
在 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)
我正在尝试根据给定的类型参数 (ET
) 实例化相应的 class(示例:CollisionEvent
)。
在您的代码中,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;
}
请注意,在 type 表达式中,CollisionEvent
指的是 class 的实例,而 typeof CollisionEvent
指的是 class 及其构造函数。