打字稿:与先前参数的已解析类型相同的通用类型

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

TypeScript playground

function add<T extends (number | string)>(a: T, b: T): T {
    if (typeof a === 'string') {
        return a + b;
    } else if (typeof a === 'number') {
        return a + b;
    }
}

add('hello', ' world');
add(1, 1);

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

最佳答案 您无法缩小函数中泛型参数的类型.因此,当您测试时,这不会告诉编译器b的类型是什么.更重要的是,它不会告诉编译器函数的返回类型是什么

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
}

在这种情况下,虽然可能有一个专用的实现签名,而不是在工会上工作(意味着不需要断言),公共签名就是你以前使用的签名:

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
}
点赞