Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redux how to use "compose" with Typescript

I have a bit issue with using compose function in Typescript, I always receive errors. The type definition in .d.ts is also quite confusing. For example:

type Props = { t: number }; 
const foo = (props: {}) => <div {...props} />;
const moo = (props: Props) => <div {...props} />;
const bar = (props: Props) => <div {...props} />;
const Dar = compose(foo, moo)(bar);

const Test = () => <Dar />;

Has several problems. It is complaining that "bar" does not have "foo" parameter (which it actually has).

Also, I cannot use since Dar is evaluated to JSX.Element not stateless function. Any IDEA with possible example of how to use compose in Typescript?

Thanks.

like image 664
tomitrescak Avatar asked Jun 09 '17 14:06

tomitrescak


People also ask

How do I use compose in Redux?

Compose is used when you want to pass multiple store enhancers to the store. Store enhancers are higher order functions that add some extra functionality to the store. The only store enhancer which is supplied with Redux by default is applyMiddleware however many other are available.

Does TypeScript work with Redux?

Overview​ TypeScript is a typed superset of JavaScript that provides compile-time checking of source code. When used with Redux, TypeScript can help provide: Type safety for reducers, state and action creators, and UI components.

Why we use compose in react JS?

React has a powerful composition model, and we recommend using composition instead of inheritance to reuse code between components. In this section, we will consider a few problems where developers new to React often reach for inheritance, and show how we can solve them with composition.


1 Answers

The inference of TypeScript works from left to right, a generic compose function composes functions from right to left, and it could lead to wrong types.

You can use a composition function which composes from left to right, like flow.

like image 94
Denis Frezzato Avatar answered Oct 22 '22 06:10

Denis Frezzato