繁体   English   中英

TypeScript 映射类型改变值函数的返回类型

[英]TypeScript mapped type change value function's return type

我有一个像这样的 TypeScript 类型:

type Api = {
  createItem: (name: string) => Promise<Item>;
  getItem: (id: number) => Promise<Item>;
  updateItem: (item: Item) => Promise<Item>;
  deleteItem: (id: number) => Promise<void>;
};

我试图弄清楚如何将其转换为以下内容:

type Api = {
  createItem: (name: string) => { type: 'success'; result: Item; } | { type: 'error' };
  getItem: (id: number) => { type: 'success'; result: Item; } | { type: 'error' };
  updateItem: (item: Item) => { type: 'success'; result: Item; } | { type: 'error' };
  deleteItem: (id: number) => { type: 'success' } | { type: 'error' };
};

我认为映射类型是 go 的一种方式:

type NewApi = {
  [_ in keyof Api]: (???) => { type: 'success'; result: ??? } | { type: 'error' }
};

我无法弄清楚如何填写那里的空白。 我什至不确定是否可以这样做。

我需要这种类型的原因是我正在构建一个网关代理,并且该类型的实际实现将是一个实际的Proxy object 拦截成员访问,mocking 他们的值与另一个代理捕获 ZC1C425268E6774 上面的联合类型。

实现部分很好,但我似乎无法获得它的类型来让 Intellisense 工作。

您可以使用打字稿参数ReturnType类型

type NewApi = {
  [K in keyof Api]: (...args: Parameters<Api[K]>) => { type: 'success'; result: ReturnType<Api[K]> } | { type: 'error' }
};

请看这个游乐场

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM