打字稿,不同的函数参数

时间:2020-06-24 17:03:12

标签: javascript typescript preact

在我的Preact应用程序内部,我使用unistore进行全局状态管理。一切正常,除了我的打字稿界面不起作用。这是因为动作(解析器)有一个额外的参数。

我的incrementBy动作有两个参数。第一个是当前状态,第二个是增加计数的数量。

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

但是当我调用函数时,我只需要指定增加的数量即可:

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

当前界面(此界面适用于组件,但(显然)不在操作内部):

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

我该如何创建一个对两者都适用的界面,所以我不必为每个动作指定多个界面。

1 个答案:

答案 0 :(得分:1)

您可能可以实现如下所示:

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 overloading