带有解构的REST参数的TypeScrip函数重载类型推理 [英] Typescript function overload type inference with deconstructed rest parameter

查看:14
本文介绍了带有解构的REST参数的TypeScrip函数重载类型推理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下重载函数:

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,但我看不到与上面的用例的连接。

推荐答案

如果允许您每晚使用打字脚本(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 甚至不使用REST参数:


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
}

这篇关于带有解构的REST参数的TypeScrip函数重载类型推理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆