typescript - 如何使用接口映射来创建新类型?
问题描述
在 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
)实例化相应的类(例如:)。
解决方案
在您的代码中,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
指的是类及其构造函数。
推荐阅读
- javascript - 如何使字段验证在自定义策略自定义 ui 上正常工作?
- oracle - 用于 oracle、db2 和 sap 的测试数据管理解决方案
- android - 谷歌地图未显示在底部导航活动片段(kotlin)中
- html - 如何更改引导程序 4 选择器的默认下拉颜色?
- php - 避免使用 Laravel 查询返回“未定义偏移量 0”表为空
- google-chrome-devtools - 如何在 Chrome 开发者控制台中访问 `copy` 功能,当它被`覆盖时
`? - makefile - 需要帮助了解为什么 ifeq 不起作用
- ios - swift UITableView中的didSelectRow事件延迟
- ios - IOS swift Web Socket SRWebSocket 设置响应超时
- excel - Microsoft Excel 公式 - 如何将函数中的单元格引用替换为其他函数