Upon reviewing the Ramda documentation regarding transduce, it was noted that two examples were provided, both resulting in different errors being thrown by the Typescript compiler.
Example 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])
})
The error message generated by Typescript for flip(append)
is as follows:
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'.
To resolve this issue, changing flip(append)
to flip(append) as any
allowed the code to function correctly.
Example 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])
})
The Typescript error for firstOddTransducer
reads as:
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 more.
Similarly, modifying firstOddTransducer
to firstOddTransducer as any
resolved the issue.
Understanding these specific errors can be complex, especially when working with functional typescript. While avoiding the use of any
or // @ts-ignore
is recommended, in practice such solutions may become necessary to prevent spending excessive time debugging types. It is essential to strike a balance between improving type safety and practicality in code development.
In situations where uncertainty arises about whether an error stems from typescript or javascript code, consider employing techniques to pinpoint the root cause. This could involve thorough code analysis, testing variations, or consulting relevant resources for assistance.