运算符"+"不能应用于类型"T"和"T".在TypeScript中 [英] Operator '+' cannot be applied to types 'T' and 'T'. in TypeScript

查看:143
本文介绍了运算符"+"不能应用于类型"T"和"T".在TypeScript中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对TypeScript非常陌生.我的TypeScript版本是3.7.5.

I am very new to TypeScript. My TypeScript version is 3.7.5.

恕我直言,它应该非常容易,但是我不知道为什么它不起作用.

IMHO, it should be very easy, but I don't know why it does not work.

function add<T> (a:T, b:T):T  {
    return a + b ;
}

console.log(add (5, 6));

我得到了错误:

运算符'+'不能应用于类型'T'和'T'.

Operator '+' cannot be applied to types 'T' and 'T'.

我也用了这个

function add<T extends string | number > (a:T, b:T):T

存在相同的错误.如果我不能为该泛型使用 + ,为什么还要使用泛型?

The same error is there. If I can not use + for this generic, why should I use generics?

推荐答案

在这里泛型不是正确的方法.您不能将 + 运算符应用于不受约束的 T (为什么要这样做?).

Generics are not the right approach here. You cannot apply the + operator to an unconstrained T (why should this work?).

函数add< T扩展字符串|数>(a:T,b:T):T 也不起作用,因为TypeScript要求至少一个操作数为 string ,在这里不是这种情况.例如,这个星座如何?

function add<T extends string | number > (a:T, b:T):T won't work either, because TypeScript requires at least one operand to be string, which is not the case here. E.g., what about this constellation:

const sn1 = 3 as number | string
const sn2 = "dslf" as number | string
add(sn1, sn2) // Both types have type number | string, sh*t...

+ 运算符不能重载,但是我们仍然可以利用

The + operator cannot be overloaded, but we can still leverage function overloads in TypeScript:

function add(a: string, b: string): string
function add(a: number, b: number): number
function add(a: any, b: any) {
    return a + b;
}

add(1, 2) // Number
add("foo", "bar") // String

这篇关于运算符"+"不能应用于类型"T"和"T".在TypeScript中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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