简体   繁体   English

为什么TypeScript在计算数字时会报错?

[英]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.

相关问题 为什么TypeScript在投射时不抱怨状态中不包含的属性? - Why does TypeScript not complain about properties not included in the state when casting? 为什么在导入组件时 typescript 会报错,但在同一文件中定义组件时不会报错? - Why does typescript complain when I import a component, but not when the component is defined in the same file? 为什么 TypeScript 在尝试从联合类型中读取 never 时不抱怨? - Why TypeScript does not complain when trying to read from never in an union type? 为什么打字稿会抱怨调用联合类型的函数? - Why does the Typescript complain with call to function of union type? 为什么TypeScript抱怨我的抽象类成员的实现? - Why does TypeScript complain about my implementation of an abstract class member? 为什么 typescript 抱怨计算的属性名称? - Why does typescript complain about a computed property name? 为什么 TypeScript 抱怨枚举上的字符串索引? - Why does TypeScript complain about string index on an enum? 为什么 Typescript 抱怨 object 不能分配给它的类型? - Why does Typescript complain that an object is not assignable to its type? 为什么打字稿不会抱怨某些未定义的变量 - Why does typescript not complain about certain undefined variables 类型上不存在属性:为什么 TypeScript 抱怨而 JavaScript 不抱怨? - Property does not exist on type: Why does TypeScript complain while JavaScript doesn't?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM