[英]Why does TypeScript complain when calculating numbers?
Let's say I have a constant number defined, eg:假设我定义了一个常数,例如:
const a = 3;
Why does TypeScript complain about this?为什么 TypeScript 抱怨这个?
const b: 10 = a * 3 + 1;
Type 'number' is not assignable to type '10'
类型“数字”不可分配给类型“10”
In the generic case, I'd like b
to have a defined set of allowed values, eg 10 | 16 | 19 | 25
在一般情况下,我希望
b
有一组定义的允许值,例如10 | 16 | 19 | 25
10 | 16 | 19 | 25
10 | 16 | 19 | 25
, and I'd like TypeScript to allow: 10 | 16 | 19 | 25
,我希望 TypeScript 允许:
const a = 3; // or 5, 6, 8
and error with all other a
s.和所有其他
a
的错误。
Is this possible?这可能吗?
When you specify the following line当您指定以下行时
const b: 10 = a * 3 + 1;
It means the const b will be a type of 10, which is not.这意味着 const b 将是 10 的类型,但不是。
For the following line对于以下行
const a = 3; // or 5, 6, 8
You will need to set the type to be as -您需要将类型设置为 -
const a: 3 | 5 | 6 | 8 = 3;
However, you can also pull it off to be a type for reusable但是,您也可以将其拉为可重复使用的类型
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.