Reputation: 1110
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.
Upvotes: 12
Views: 3884
Reputation: 968
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.
Upvotes: 1
Reputation: 1641
compose
is a function that combines two functions assuming the output type of the first function matches the input type of the second function.
const compose = (f,g) => x => f(g(x))
So what you're saying in your compose line is that you want to apply bar
(which is a function from Props
to JSX.Element
) as an argument to moo
which is also a function from Props
to JSX.Element
and then take the result of that and apply it to foo
.
The problem is that
moo
doesn't accept a function fromProps
toJSX.Element
, it acceptsProps
If you want to return a "stateless function" you'll need to use this template to tell Typescript that's what you want
const bar: React.FunctionComponent<Props> = (x: Props) => <div {...props} />;
Upvotes: 0