打字稿:与上一个参数的解析类型相同的通用类型 [英] Typescript: Same generic type as resolved type of previous parameter

查看:61
本文介绍了打字稿:与上一个参数的解析类型相同的通用类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道,当类型可以是多种类型时,如何指定与上一个参数的解析类型相同的泛型类型.

I would like to know, how to specify that generic type if same as the one the resolved type of previous argument, when the type can be of multiple types.

我希望能够告诉编译器所有T都是相同的类型,无论是数字还是字符串.我可能会错过一些语法.条件类型(在某种程度上)可能是可能的...

I want to be able to tell the compiler that all T are of same type, either number or string. I might missed some syntax. It might be possible with conditional types (to some extend)...

推荐答案

您不能在函数内缩小泛型参数的类型.因此,当您测试a时,这不会告诉编译器b的类型是什么.更重要的是,它不会告诉编译器函数的返回类型是什么

You can't narrow the type of the generic parameter within the function. So when you test a this will not tell the compiler what the type of b is. And more importantly it will not tell the compiler what the return type of the function needs to be

function add<T extends (number | string)>(a: T, b: T): T {
    if (typeof a === 'string' && typeof b === 'string') {
        let result = a + b; // result is string, we can apply + 
        return result as T; // still an error without the assertion, string is not T 
    } else if (typeof a === 'number' && typeof b === 'number') {
        let result = a + b; // result is number, we can apply +
        return result as T; // still an error without the assertion, number is not T  
    }
    throw "Unsupported parameter type combination"; // default case should not be reached
}

在这种情况下,尽管也许有一个专用的实现签名可以在联合上工作(这意味着不需要断言),而公共签名是您先前使用的签名.:

In this case though maybe having a dedicated implementation signature that works on the union instead (meaning no assertion is required) and public signature being the one you previously used.:

function add<T extends number | string>(a: T, b: T): T
function add(a: number | string, b: number | string): number | string {
    if (typeof a === 'string' && typeof b === 'string') {
        return a + b;
    } else if (typeof a === 'number' && typeof b === 'number') {
        return a + b;
    }
    throw "Unsupported parameter type combination"; // default case should not be reached
}

这篇关于打字稿:与上一个参数的解析类型相同的通用类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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