Anton Telesh
Anton Telesh

Reputation: 3822

Typescript point to function

I'm writing a reactjs application using TypeScript and redux. To describe components props I'm using interfaces instead of propTypes. That allowes me to check prop types at compile time.

Some of the props are functions (redux action creators, wrapped by connect with dispatch).

How to say TypeScript that my component property is of that action creator function signature? I mean I don't want to repeat describing types.

To understand more the question, look at the example below:

// here is my action creator
function someAction(prop1: number, prop2: string) {
  ...
}

interface IComponentProps {
  // here I want to say
  // that this is the same function as above,
  // but I have to duplicate its type signature
  someAction(prop1: number, prop2: string);
}

Of course, I can create an interface for that function:

interface ISomeActionFunction {
  (prop1: number, prop2: string): void
}

and then use it in both function declaration and properties interface, but I wonder if there is any way to point to the specific function directly?

Upvotes: 2

Views: 467

Answers (1)

user1233508
user1233508

Reputation:

As you've already realised, using an interface is your best approach here. You can make it look like this:

interface IComponentProps {
    someAction: ISomeActionFunction;
}

interface ISomeActionFunction {
    (prop1: number, prop2: string): void;
}

const someAction: ISomeActionFunction = (p1, p2) => {
    // the compiler will correctly infer the types of p1 and p2 for you
    ...
}

This way, the function types are not repeated and the compiler can still check everything.

If you foresee a need for a lot of action creators, you can add a generic helper like this:

interface IBinaryActionCreator<T1, T2, TResult> {
  (prop1: T1, prop2: T2): TResult;
}

type ISomeActionFunction = IBinaryActionCreator<number, string, void>;

But that may be overkill.

Upvotes: 2

Related Questions