【问题标题】:Typescript function overload type inference with deconstructed rest parameter带有解构的剩余参数的打字稿函数重载类型推断
【发布时间】:2022-01-03 15:45:14
【问题描述】:

给定以下重载函数:

foo(tool: 'a', poaram: boolean, poarama: number): boolean
foo(tool: 'b', paramo: string, paramoa: string): boolean
foo(tool: 'a' | 'b', ...args: any[]): boolean {
    if (tool === 'a') {
        const [ poaram, poarama ] = args

    }

    return false
}

有什么方法可以让poarampoarama 分别输入为any 而不是booleannumber

我知道Tuples in rest parameters and spread expressions,但我看不到与上述用例的联系。

【问题讨论】:

  • 您需要将它们全部作为其余参数的一部分。请参阅示例 tsplay.dev/w14nyW 。请让我知道这对你有没有用。在这种情况下,您甚至不需要重载您的函数。另请记住,它仅适用于 TS nightly,4.6

标签: typescript typescript-typings


【解决方案1】:

如果你被允许每晚使用 TypeScript (4.6),你可以考虑这个解决方案:


function foo(...args: ['a', boolean, number] | ['b', string, string]): boolean {
    const [fst, scd, thrd] = args;
    if (fst === 'a') {
        const x = scd; // boolean
        const y = thrd // number

    }

    return false
}

Playground 甚至没有休息参数:


function foo([first, second, third]: ['a', boolean, number] | ['b', string, string]): boolean {
    if (first === 'a') {
        const x = second; // boolean
        const y = third // number

    }

    return false
}

这里添加了以上功能TypeScript/pull/46266

如果不允许,则应避免元组解构:


function foo(...args: ['a', boolean, number] | ['b', string, string]): boolean {
    if (args[0] === 'a') {
        const x = args[1]; // boolean
        const y = args[2] // number

    }

    return false
}

【讨论】:

  • 要将第一个参数分配给toolfoo([tool, ...args]: ['a', boolean, number] | ['b', string, string]): boolean 也应该可以,对吧?
  • @DustInCompetent 它看起来不像那样工作。我不能说我对这个新功能非常熟悉,因此无法为您提供详尽的解释。只是没有机会深入研究它。它甚至还没有发布
【解决方案2】:

您可以为函数的实现类型选择其中之一:

foo(tool: 'a'|'b', ...args: [boolean, number]|[string, string]): boolean { // or
foo(tool: 'a'|'b', arg1: boolean|string, arg2: number|string): boolean {

【讨论】:

  • 确实如此。但我一直在寻找一种不明确写出...args 类型的方法:)
猜你喜欢
  • 1970-01-01
  • 2019-02-22
  • 1970-01-01
  • 2019-09-15
  • 1970-01-01
  • 2020-03-22
  • 2020-03-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多