簡體   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