带打字稿的 RamdaJs,避免点自由时的错误

RamdaJs with typescript, avoid errors when point free

const getColumnsBySection = R.pipe(
    R.filter(c => c.section != null),
    R.groupBy(c => c.section)
  );

当在这个函数中使用 RamdaJs 的 point free 时。我收到打字稿错误

 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'

您认为如何使用无点函数而不会出现此类打字稿错误?

考虑以下代码:

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"}))

如果我们从第一个组合函数中去掉 Monkey 类型,Typescript 不可能知道传递给它的 m 参数有一个 name 属性,因此无法正确键入结果函数的参数 p.

但是,对于传递给 pipe 的后续函数,由于 @types/ramda 中的类型,R.pipe 能够从 [=27] 中正确推断出这些组合函数的类型=] 参数列表中的前一个函数。

Codesandbox link

您可以将函数转换为您期望的类型,或者您可以更多地依赖于 ramda 库,而不是像这样的构造:

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>