TypeScript 数组泛型丢失顺序

标签 typescript

我有一个接收数组 ([a,b]) 作为第二个参数的函数。我们不知道它在函数中的类型,因此我们为此创建了一个泛型。

数组被传递给该函数中的回调。

稍后在回调中使用时,数组已失去其类型顺序。 TypeScript 认为数组可以是 [b,a] 和 [a,b],因为它的泛型是 (a|b)[] 而不是 [a,b]。

可以通过将类型传递给函数来覆盖泛型来完成,但我想避免这种情况。

两个 console.logs 给出类型错误。我如何制作一个遵循数组顺序的泛型?

以下代码在 TypeScript Playground. 中运行

function useOnChange<Dependencies extends Array<unknown>>(callback: (oldValue: Dependencies) => void, dependencies: Dependencies) {
    callback(dependencies);    
}

const a = { test: "something"}
const b = { test2: "else" }

useOnChange(([a,b]) => {
    // I array destruct the argument by their index in the array
    // Therefore a === a and b === b.
    // But TypeScript thinks the argument (which we destructed) is (a|b)[] and not [a,b].
    // In other words: It thinks it could be [b,a] as well as it could be [a,b]. It ignores the order of the array.

    console.log(a.test);
    console.log(b.test2);
}, [a,b])

// This works, but I believe it shouldve worked without
useOnChange<[{test: string}, {test2: string}]>(([a,b]) => {
    console.log(a.test);
    console.log(b.test2);
}, [a,b])

最佳答案

一般休息应该可以解决问题。解释于:https://medium.com/javascript-in-plain-english/typescript-generic-rest-parameters-and-tuple-types-in-practice-edc2bb0bdcb9

function useOnChange<T extends unknown[]>(callback: (oldValue: [...T]) => void, dependencies: [...T]) {
  callback(dependencies);    
}

const a = { test: "something"}
const b = { test2: "else" }

useOnChange(([a,b]) => {
  console.log(a.test);
  console.log(b.test2);
}, [a,b])

关于TypeScript 数组泛型丢失顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65613262/

相关文章:

javascript - 如何在两个 ngFor 中获取有序索引?

angular - 使用 Observable 或 Promise 在 Angular 6 中转换管道

html - 无法显示 tinymce

node.js - 如何使用 Gramjs 和 Telegram API 下载媒体文件?

angular - 为什么没有 <app-root> 的其他组件不会出现在 index.html 上?

typescript - 如何使用 npm 链接和使用 TypeScript 编写的模块进行开发?

typescript - 如何在 Typescript 中使用 'dialogflow' 客户端库?

typescript - Jasmine Spec Helpers 未加载

typescript - Chai 期望使用 Typescript 抛出与相同异常不匹配的异常

class - 从另一个 *.ts 文件创建 typescript 的对象