【问题标题】:Cannot add string | number to string | number types in typescript无法添加字符串 |数字到字符串 |打字稿中的数字类型
【发布时间】: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

为什么我不能这样做?

【问题讨论】:

标签: javascript typescript typescript-typings


【解决方案1】:

这里的错误情况是number + number | string

您可以验证以下功能无效。

function addOne(x: number | string) {
  return 1 + x;
}

来自打字稿github page

如果T extends string | numberT 可以是string | number,这意味着T 类型的一个值可以是string 类型T 的不同值可以是number

听起来你应该在这里使用重载而不是类型参数。

【讨论】:

  • 但是根据这个定义,如果两者都是数字——没关系,如果一个数字和一个字符串——没关系。当您尝试添加数字和数字 |字符串,只有这两种情况会发生。似乎打字稿不够聪明,无法弄清楚
猜你喜欢
  • 2022-01-03
  • 2023-02-03
  • 2021-03-09
  • 1970-01-01
  • 1970-01-01
  • 2018-04-28
  • 2020-05-08
  • 2022-07-08
  • 2015-12-22
相关资源
最近更新 更多