首页 > 解决方案 > 从接口中删除泛型

问题描述

有没有办法从接口中删除泛型?
代码示例:

我有:

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 个小时,但还没有找到答案。很高兴得到帮助

标签: typescripttypescript-generics

解决方案


使用带有推断参数的条件类型的解决方案:

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


推荐阅读