typescript - 从接口中删除泛型
问题描述
有没有办法从接口中删除泛型?
代码示例:
我有:
interface ServerMessages {
[ActionType.EVENT_1]: ResponseEventBody1;
[ActionType.EVENT_2]: ResponseEventBody2;
[ActionType.EVENT_3]: ResultModifier<ResponseEventBody3>;
[ActionType.EVENT_4]: ResponseEventBody4;
[ActionType.EVENT_5]: ResultModifier<ResponseEventBody5>;
[ActionType.EVENT_6]: ResultModifier<ResponseEventBody6>;
[ActionType.EVENT_7]: ResponseEventBody7;
}
interface ResultModifier<T> {
success: boolean;
payload: T;
error?: SomeError;
}
我想收到的:
interface ServerMessagesWithoutGenerics {
[ActionType.EVENT_1]: ResponseEventBody1;
[ActionType.EVENT_2]: ResponseEventBody2;
[ActionType.EVENT_3]: ResponseEventBody3;
[ActionType.EVENT_4]: ResponseEventBody4;
[ActionType.EVENT_5]: ResponseEventBody5;
[ActionType.EVENT_6]: ResponseEventBody6;
[ActionType.EVENT_7]: ResponseEventBody7;
}
我已经搜索了 3 个小时,但还没有找到答案。很高兴得到帮助
解决方案
使用带有推断参数的条件类型的解决方案:
type Unmodify<T> = T extends ResultModifier<infer U> ? U : T
type UnmodifyInterface<T> = {[K in keyof T]: Unmodify<T[K]>}
type ServerMessagesWithoutGenerics = UnmodifyInterface<ServerMessages>
请注意,如果任何ResponseEventBody
类型碰巧可分配给ResultModifier<U>
some ,这将给出不正确的结果U
。
推荐阅读
- php - Laravel 8:将刀片加载到另一个刀片时未定义的变量
- java - testcontainers - 无法连接到通用容器的暴露端口
- python - 烧瓶分页重定向
- c# - 使用 Linq 查询在 JObject 数组属性中查找放在同一作业中的外部
- php - 如何在 Symfony 5.3 的控制器中获取 Session 对象?
- c++ - 错误 NO 24:无法写入总线打开的文件太多
- java - 放心,无法为 Post 调用提取 JSON 响应
- camera - 关于D435避障方式的问题
- javafx - 从文件位置运行 Java 中的 .deb 文件
- python - 在 Python 中为值分配维度