带打字稿的RamdaJs,避免在没有指针时出错

问题描述

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

与此功能一起在RamdaJs中使用无点时。我收到打字稿错误

 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'

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

解决方法

您可以将函数强制转换为所需的类型,也可以使用以下结构代替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'},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>

,

考虑以下代码:

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属性,因此可以' t正确键入结果函数p的参数。

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

Codesandbox link