从接口中删除泛型
Remove generics from interface
有没有办法从界面中删除泛型?
代码示例:
我有:
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
类型恰好可分配给某些 U
的 ResultModifier<U>
。
,这将给出不正确的结果
有没有办法从界面中删除泛型?
代码示例:
我有:
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
类型恰好可分配给某些 U
的 ResultModifier<U>
。