RamdaJs with typescript, avoid errors when point free

814 Views Asked by At
const getColumnsBySection = R.pipe(
    R.filter(c => c.section != null),
    R.groupBy(c => c.section)
  );

When using point free with RamdaJs as in this function. I get typescript errors

 Type 'Dictionary<unknown>' is missing the following properties from type 'readonly unknown[]': length, concat, join, slice, and 18 more.
TS2339: Property 'section' does not exist on type 'unknown'

How are you suppose to use point free functions without getting typescript errors like these?

2

There are 2 best solutions below

0
On BEST ANSWER

You can either cast the function to the types you expect, or you can lean more on the ramda library with a construction like this instead:

const { anyPass, complement, pipe, propSatisfies, filter, groupBy, prop, isNil, isEmpty } = R

const isBlank = anyPass([isNil, isEmpty]);

const isPresent = complement(isBlank);

const getColumnsBySection = pipe(
  filter(propSatisfies(isPresent, 'section')),
  groupBy(prop('section'))
);

const samples = [
  {section: 'trees', name: 'birch'}, 
  {section: 'vines', name: 'grape'},
  {section: 'trees', name: 'cedar'},
  {section: 'vines', name: 'ivy'},
];

const results = getColumnsBySection(samples);
console.log(results);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js"></script>

0
On

Consider the following code:

import * as R from "ramda"

interface Monkey{
  name:string;
}

const p = R.pipe(
  (m: Monkey) => `cheeky-${m.name}`, // `m` can't be inferred, hence type annotation
  (s) => `hello ${s}` // here `s` *can* be inferred
)

console.log(p({name:"monkey"}))

If we take away the Monkey typing from the first composed function, Typescript can't possibly know that the m argument being passed to it has a name property and therefore can't correctly type the arguments of the resulting function p.

However, for subsequent functions passed to pipe, due to the typings in @types/ramda, R.pipe is able to correctly infer the typing of these composed functions from the return-type of the previous function in the argument list.

Codesandbox link