![](/img/trans.png)
[英]TypeScript same function arguments type with different implementation
[英]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});
interface IActions { incrementBy(num: number): State; incrementBy(state: State, num: number): State; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.