2

查看transduce的 Ramda 文档,给出了两个示例,每个示例都会导致 Typescript 编译器抛出不同的错误。

示例 1:

test('ex. 1', () => {
  const numbers = [1, 2, 3, 4]

  const transducer = compose(
    map(add(1)),
    take(2)
  )

  const result = transduce(transducer, flip(append), [], numbers)

  expect(result).toEqual([2, 3])
})

Typescript 引发以下异常flip(append)

Argument of type '(arg1: never[], arg0?: {} | undefined) => <T>(list: readonly T[]) => T[]' is not assignable to parameter of type '(acc: ({} | undefined)[], val: {} | undefined) => readonly ({} | undefined)[]'.
      Types of parameters 'arg1' and 'acc' are incompatible.
        Type '({} | undefined)[]' is not assignable to type 'never[]'.
          Type '{} | undefined' is not assignable to type 'never'.
            Type 'undefined' is not assignable to type 'never'.

如果我更改flip(append)代码flip(append) as any按预期工作。

示例 2:

test('ex. 2', () => {
  const isOdd = x => x % 2 === 1
  const firstOddTransducer = compose(
    filter(isOdd),
    take(1)
  )

  const result = transduce(
    firstOddTransducer,
    flip(append) as any,
    [],
    range(0, 100)
  )

  expect(result).toEqual([1])
})

Typescript 引发以下异常firstOddTransducer

Argument of type '(x0: readonly any[]) => Dictionary<any>' is not assignable to parameter of type '(arg: any[]) => readonly any[]'.
      Type 'Dictionary<any>' is missing the following properties from type 'readonly any[]': length, concat, join, slice, and 16 more.

与上面相同,如果我更改firstOddTransducer代码firstOddTransducer as any按预期工作。

首先,这些特定的错误甚至意味着什么?

其次,用函数式打字稿处理这类问题的最佳方法是什么?因此,在查看各种 typescript 学习资源时,经常会警告用户不要使用any或反对使用// @ts-ignore,好像它是你不应该做的事情,但是我的代码库越复杂,我的编程风格变得越实用,这些内容就越多缝合我收到的完全可接受的代码的难以理解的错误消息。我不介意花一点时间来改进类型,但是当我知道代码很好时,我不想花太多时间调试类型的问题。

第三,当您不确定类型或打字稿是否存在问题时,是否有任何提示可以提供帮助,如上所述,或者 JavaScript 代码是否存在问题,例如,确定位置的技术实际的问题是你可以调查还是忽略?

4

1 回答 1

1

在撰写本文时,这是 TypeScript 的一个限制,您根本无法表达必须从以后的使用中推断出类型的一部分。

直到你调用transduce你才真正绑定所有类型参数,所以直到那时它才不是一个完整的类型,或者更确切地说,TypeScript 在你这样做之前不知道如何完成类型。TypeScript 将尝试从上下文推断类型,所以也许,如果你把所有这些放在一行上,它可能能够做到这一点(不是说它会这样做)。

从根本上说,传感器是序列/流/可观察的抽象,当您在某些数据上实际运行传感器时,您会授予编译器此信息。这时候就需要绑定数据的类型信息了。

我在这里唯一能想到的是,在unknown运行transduceinto. 它不会授予您类型安全性,但会抑制编译器警告,无论哪种方式都是误报。它并不完美,但它应该可以工作。

于 2020-02-13T07:11:52.407 回答