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

标签 typescript generics

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

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 都是相同的类型,要么是数字,要么是字符串。我可能错过了一些语法。条件类型(在某种程度上)可能是可能的......

最佳答案

您不能缩小函数内泛型参数的类型。因此,当您测试 a 时,这不会告诉编译器 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
}

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

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
}

关于 typescript :与先前参数的已解析类型相同的通用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51248339/

相关文章:

typescript - 英特尔lij : how to change the syntax of extracted function in typescript?

javascript - 使用 TypeScript 2.0 导入 js 文件

c# - 在泛型约束中通过构造函数传递参数

c# - 使用 EF Core 更新通用存储库上的父集合和子集合

java - 什么是原始类型,为什么我们不应该使用它呢?

angularjs - TypeScript 编译器查看 node_modules 的外部目录

javascript - "regular"客户端开发可以使用编译为 JavaScript 的工具吗?

javascript - Nativescript 和 Angular 2 Http 服务

java - java中的简单泛型列表

c++ - Java 通配符在 C++ 中的等价物是什么?