簡體   English   中英

Typescript,不同 function arguments

[英]Typescript, different function arguments

在我的 Preact 應用程序中,我使用unistore進行全局 state 管理。 一切正常,只是我的 typescript 接口不工作。 這是因為動作(解析器)有一個額外的參數。

我的incrementBy操作是獲取兩個 arguments。 第一個是當前的 state,第二個是增加計數的數量。

// Inside action (resolver)
incrementBy: (state, num): State => {
  return { ...state, count: state.count + num };
};

但是當我調用 function 時,我只需要指定要增加的數量:

// Inside component
<button onClick={() => incrementBy(8)}>
  Increase by 8
</button>

當前界面(這適用於組件,但(顯然)不在動作內部):

interface Actions {
  incrementBy(num: number): State;
}

我怎樣才能制作一個同時適用於兩者的單一界面,所以我不必為每個操作指定多個界面。

你可能可以實現這樣的事情:

export interface IIncrementParams {
  state?: State;
  num?: number;
}

interface IActions {
  incrementBy(params: IIncrementParams): State;
}

這將允許您執行以下操作:

incrementBy({num: 8});
incrementBy({state: someState});
incrementBy({state: someState, num: 8});

選項 2 是您可以提供多個簽名:
 interface IActions { incrementBy(num: number): State; incrementBy(state: State, num: number): State; }

TypeScript function 過載

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM