简体   繁体   English

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

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

I have a TypeScript type like this:我有一个像这样的 TypeScript 类型:

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

And I'm trying to figure out how to convert it to the following:我试图弄清楚如何将其转换为以下内容:

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' };
};

I think mapping types are a way to go here:我认为映射类型是 go 的一种方式:

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

I'm unable to figure out how to fill in the blanks there though.我无法弄清楚如何填写那里的空白。 I'm not even sure it is possible to do that.我什至不确定是否可以这样做。

The reason I need this type is that I am building a gateway proxy and the actual implementation of the type will be an actual Proxy object intercepting the member accesses, mocking their values with another proxy which traps function invocation for a change and returns the above union type.我需要这种类型的原因是我正在构建一个网关代理,并且该类型的实际实现将是一个实际的Proxy object 拦截成员访问,mocking 他们的值与另一个代理捕获 ZC1C425268E6774 上面的联合类型。

The implementation part is fine, but I can't seem to be able to get the type for it to get Intellisense working.实现部分很好,但我似乎无法获得它的类型来让 Intellisense 工作。

You can make use of typescripts Parameters and ReturnType types您可以使用打字稿参数ReturnType类型

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

Please see this playground .请看这个游乐场

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

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