【问题标题】:typing an array where i know the type of the first value but but i don't know the array length neither the type of all other value键入一个数组,我知道第一个值的类型,但我不知道数组长度,也不知道所有其他值的类型
【发布时间】:2021-09-02 14:59:01
【问题描述】:

我有以下函数,它接受任意数量的参数。但是,我知道第一个参数必须是一个函数,其他参数可以是任何东西,我不知道数组的长度。 我应该为已知第一个元素但未知长度和其他类型的数组类型赋予什么形状?

// i tried also ...args: [Function, any], but eslint does not like the generic 'Function' type and throw an error

function test(...args: Array<????>) {
 const [callbackFn, ...restOfArgs] = args;
 // do whatever
}

【问题讨论】:

    标签: typescript


    【解决方案1】:

    您可以拆分第一个参数,然后使用“...”语法来捕获其余参数。将() =&gt; void 替换为您的回调函数类型。

    function test(callbackFunction: () => void, ...args: unknown[]): void {
      callbackFunction()
      // access the rest of the arguments as you would from an array
    }
    

    https://www.typescriptlang.org/play?#code/LAKAZgrgdgxgLgSwPZQARwKYGc4AoYCGANkQEYEwDWAYtPMlAFyq4CUqAvAHyoBuSCACYAaVADoJBAE4BzLM2iUoSAO5QA2gF1WzfkNQBvUKlSES5KrViIUbUAF9QQA

    编辑:我意识到我没有完全回答这个问题。如果您想将所有参数保留在同一个变量下,您可以这样做:

    function test(...args: [() => void, ...unknown[]]): void {
      args[0]()
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-19
      相关资源
      最近更新 更多