Skip to content
Advertisement

Cannot create type as specific number when number is in variable

I want to create a type that can be only 1 or root 2. This works:

JavaScript

But when I try to use Math.SQRT2, or any variable reference to the numeric value of root 2, I get an error. For example:

JavaScript

Typescript playground demonstrating the issue

In my code I want to be able to reference the root of 2 with to a uniform number of decimal places. I don’t want to have to write 1.4142135623730951 every time. Why am I getting a type error when trying to use Math.SQRT2, or the value as a variable?

Advertisement

Answer

Why am I getting a type error when trying to use Math.SQRT2, or the value as a variable?

In order to use a value as a type, you need to use typeof:

JavaScript

However, this won’t give you what you want, because typescript infers a numeric literal as a number instead of the explicit value of that number, which makes typeof root2 equal to number. If you want it to be typed as the numeric literal 1.4142135623730951, you can use a const assertion, which narrows the type to the literal value:

JavaScript

In regards to Math.SQRT2, the type definition has it typed as a number, so you won’t be able to use it as a literal type unless you typecast it:

JavaScript

If you’re doing that, you’re better off just exporting your own set of constant values like root2.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement