typescript - 如何在 TypeScript 中创建适用于数字和字符串的通用加法运算符
问题描述
在学习 TypeScript 中的泛型时,我想尝试重新创建以下 JavaScript:
function add(x, y){
return x + y;
}
我试过像:
type StringOrNumber = string | number;
function add<MyType extends StringOrNumber>(x: MyType, y: MyType): MyType {
return x + y;
}
这与以下错误有关:
error TS2365: Operator '+' cannot be applied to types 'MyType' and 'MyType'.
为什么这不起作用?我假设它MyType
可能是一个字符串或一个数字,一旦“选择”TypeScript 就会知道它是添加两个字符串还是两个数字。
解决方案
也可能发生的情况是 that MyType
can be string | number
which extends
StringOrNumber
。例如add<string | number>('', 1);
,使用您定义的签名对函数进行完全有效的调用。扩展联合类型的类型并不意味着“选择一个”。
由于您的签名是有意义的,并且您正在学习泛型,所以我们想坚持使用它,我们也可以在那时关闭类型检查。有时打字稿真的无法弄清楚你的复杂场景,你别无选择,return (x as any) + y
只能放弃此时的类型检查。
处理这种情况的另一种方法是使用重载签名,如下所示
function add(x: string, y: string): string;
function add(x: number, y: number): number;
function add(x: any, y: any): any {
return x + y;
}
const t1: string = add(10, 1); // Type 'number' is not assignable to type 'string'.
const t2: number = add(10, 1); // OK
const t3: string = add('10', '1'); // OK
const t4: number = add('10', 1); // Argument of type '"10"' is not assignable to parameter of type 'number'.
推荐阅读
- android - 如何在 React Native 应用程序在前台显示 FCM
- azure-devops - 您可以自定义 VSTS 发布定义的构建版本下拉列表吗
- c++ - 如何从处于低功耗状态的 USB 设备获取字符串描述符?
- plot - 在 Mathematica 中绘制多条网格线并给出单独的标签
- python - 在 Python 3 中哪个更适合字符串反转?
- sqlite - 在服务器上使用带有 TCL/sqlite3 的 ORDER BY 时出错
- bash - 在不同服务器和端口上执行 netcat 操作的 Bash 脚本
- javascript - Dialogflow 完成响应
- typo3 - TYPO3:将类别传递给掩码内容元素
- python - Flask 首次运行:不要在生产环境中使用开发服务器