typescript error when comparing two arrays with different types

未关闭 适合新手
#741 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 1 天内回复

还没有人认领这个 Issue。

评估

难度
2/5
预计耗时
1-3 小时
新手友好度
76/100
Issue 类型
缺陷
描述清晰度
描述清楚
活跃度
活跃

调研方向

阅读链接行中的 src/diff/array.ts 里的 diffArrays 声明,并将其泛型签名与 issue 中展示的旧版 @types/jsdiff 签名进行比较。检查相关的数组 diff 选项类型和结果类型,然后复现示例中的 TypeScript 错误。当元素类型不同的数组能够搭配类型正确的 comparator 被接受,且结果能够表示这两种元素类型时,即为完成。

由索引模型根据 Issue 内容生成。

描述

in my codebase i deliberately compare arrays of two different types, with a custom comparator to compare them in a typesafe way, for example:

import { diffArrays } from 'diff';


const array1 = [1, 2, 3];

const array2 = ['1', '2'];

const result = diffArrays(array1, array2, {
    comparator: (oldValue, newValue) => oldValue.toString() === newValue }
);

this no longer works since updating jsdiff to the version with bundled typescript types:

asdf.ts:7:35 - error TS2769: No overload matches this call.
  The last overload gave the following error.
    Argument of type 'string[]' is not assignable to parameter of type 'number[]'.
      Type 'string' is not assignable to type 'number'.

7 const result = diffArrays(array1, array2, { comparator: (oldValue, newValue) => oldValue.toString() === newValue });
                                    ~~~~~~

  node_modules/.pnpm/[email protected]/node_modules/diff/libesm/diff/array.d.ts:17:25
    17 export declare function diffArrays<T>(oldArr: T[], newArr: T[], options?: DiffArraysOptionsNonabortable<T>): ChangeObject<T[]>[];
                               ~~~~~~~~~~
    The last overload is declared here.

asdf.ts:7:58 - error TS7006: Parameter 'oldValue' implicitly has an 'any' type.

7 const result = diffArrays(array1, array2, { comparator: (oldValue, newValue) => oldValue.toString() === newValue });
                                                           ~~~~~~~~

asdf.ts:7:68 - error TS7006: Parameter 'newValue' implicitly has an 'any' type.

7 const result = diffArrays(array1, array2, { comparator: (oldValue, newValue) => oldValue.toString() === newValue });

playground

it used to work in @types/jsdiff because it used two generics:

export function diffArrays<TOld, TNew>(
    oldArr: TOld[],
    newArr: TNew[],
    options?: ArrayOptions<TOld, TNew>,
): Array<ArrayChange<TOld | TNew>>;

whereas the new version only uses one generic:

https://github.com/kpdecker/jsdiff/blob/8d706c8f2c17283d1061308113c95146a5118aa6/src/diff/array.ts#L24-L55

主要语言
JavaScript
星标
9.2k
派生
555
平均合并
1 天 9 小时
30 天内合并 PR
5

环境准备

  • 没有 Dockerfile 或 Docker Compose 文件
  • 没有 Pull Request 模板
  • 阅读贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

kpdecker/jsdiff 的其他 Issue

查看 kpdecker/jsdiff 的全部 Issue

相似的 Issue

更多 JavaScript Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。