简体   繁体   中英

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?

const b: 10 = a * 3 + 1;

Type 'number' is not assignable to type '10'

In the generic case, I'd like b to have a defined set of allowed values, eg 10 | 16 | 19 | 25 10 | 16 | 19 | 25 10 | 16 | 19 | 25 , and I'd like TypeScript to allow:

const a = 3; // or 5, 6, 8

and error with all other a s.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM