Search code examples
javascripttypescriptpreact

Typescript, different function arguments


Inside my Preact application i use unistore for global state management. It all works fine except that my typescript interface is not working. This is because the actions (resolvers) are having an extra argument.

My incrementBy action is getting two arguments. The first one is the current state and the second one is the amount to increase the count by.

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

But when i call the function i only need to specify the amount to increase by:

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

Current interface (this works for the component but (obviously) not inside the action):

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

How can i make a single interface which works for both, so i dont have to specify multiple interfaces for every action.


Solution

  • You can probably implement something like this:

    export interface IIncrementParams {
      state?: State;
      num?: number;
    }
    
    interface IActions {
      incrementBy(params: IIncrementParams): State;
    }
    

    Which would allow you to do:

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

    Option 2 is you could provide multiple signatures:
    interface IActions {
      incrementBy(num: number): State;
      incrementBy(state: State, num: number): State;
    }
    

    TypeScript function overloading