查看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 代码是否存在问题,例如,确定位置的技术实际的问题是你可以调查还是忽略?