2

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?

3
  • mmm, maybe you want something like (arg:sometype, argb:SecondType)=>ReturnType? So this expression can be used like this Commented Dec 31, 2015 at 9:12
  • You can try someAction: typeof someAction but I believe it's a bad practice. You should define the type twice or just not pass it as a prop. Commented Dec 31, 2015 at 10:11
  • I want that function to be linked to that property. So that when I change function signature in a precess of refactoring, the compiler would argue. Seems like it only could be done by creating interface. Commented Dec 31, 2015 at 12:49

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.