0

Let's say I have a constant number defined, e.g.:

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, e.g. 10 | 16 | 19 | 25, and I'd like TypeScript to allow:

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

and error with all other as.

Is this possible?

Misha Moroshko
  • 166,356
  • 226
  • 505
  • 746
  • const a: 1 | 2 | 3 = 1; const a: number = 1 – Joseph Walker Aug 08 '22 at 12:16
  • Does this answer your question? [Is it possible to restrict number to a certain range](https://stackoverflow.com/questions/39494689/is-it-possible-to-restrict-number-to-a-certain-range) – Croolman Aug 08 '22 at 12:34
  • You might be interested in [this](https://stackoverflow.com/questions/69089549/typescript-template-literal-type-how-to-infer-numeric-type#answer-69090186) answer or [this](https://catchts.com/range-numbers) article. However, `number` type is still wider than any range. It is not safe to rely on literal number type if you perform Math calculations – captain-yossarian from Ukraine Aug 08 '22 at 14:08

1 Answers1

0

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

Avi Siboni
  • 686
  • 7
  • 16