如何用基于映射类型的TypeScript条件类型优化API响应类型处理
类型安全通信中根据API类型自动返回单值或数组的实现方案
我正在开发类型安全的客户端/服务端通信机制,使用映射类型定义请求所需参数及响应返回值,示例类型如下:
export interface IProtocolParameters { "authenticate": { username: string; password: string }; "getLogLevel": {}; }
以及响应结果类型:
export interface IProtocolFinalResult { "authenticate": { activeProfile: ICommShellProfile }; "getLogLevel": { result: string }; }
但部分API会返回多个响应,因此我将实际响应类型及返回它的Promise定义为:
export type ResponseType<K extends keyof IProtocolFinalResult> = Array<IProtocolFinalResult[K]> | IProtocolFinalResult[K]; export type ResponsePromise<K extends keyof IProtocolFinalResult> = Promise<ResponseType<K>>;
这带来了不便:每次消费结果时都必须先判断是否为数组,示例代码如下:
public async getLogLevel(): Promise<string> { const response = await MessageScheduler.get.sendSimpleRequest({ requestType: "getLogLevel", parameters: {}, }); return Array.isArray(response) ? response[0].result : response.result; }
尤其是在拥有上百个API的情况下,这种操作十分繁琐。我希望通过条件类型来改进,根据API的不同,返回IProtocolFinalResult[K]的数组或单个值。
根据文档,条件类型只能基于继承实现,无法基于其他条件(如标记或映射类型等)。我设想的实现方式如下:
export type ResponseType<K extends keyof IProtocolFinalResult> = multiResults.has(K) ? Array<IProtocolFinalResult[K]> : IProtocolFinalResult[K];
其中:
const multiResults: Set<string> = new Set(["listSomething"]);
请问有没有其他可行的实现方案?
内容的提问来源于stack exchange,提问作者Mike Lischke
相关产品推荐
相关产品推荐

