【发布时间】:2021-05-30 00:45:41
【问题描述】:
所以,我有类型别名 T 代表 string | number 联合类型
如果我尝试添加两个这种类型的变量,我将得到类型为T 的变量。但是如果我将这两个变量作为函数的参数,那将是一个错误:
type T = string | number;
function add(a: T, b: T): T{
return a + b;
// Error: Operator '+' cannot be applied to types 'T' and 'T'.
}
let a: T = 1;
let b: T = 'foo';
const c = a + b; // But this is ok
为什么我不能这样做?
【问题讨论】:
-
typescript + operator usage on union types 的完全相同的副本(不幸的是没有答案)。另请参阅Operator '+' cannot be applied to types 'T' and 'T'. in TypeScript(名义上的
T指的是泛型,而不是别名,但答案处理相同的情况)
标签: javascript typescript typescript-typings