Skip to content

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:

type OneOrRootTwo = 1 | 1.4142135623730951;

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:

type OneOrRootTwo = 1 | Math.SQRT2; // Math is a type, not a namespace error

const root2 = 1.4142135623730951;
type OneOrRootTwo = 1 | root2; // root2 is a value but is being used a type error

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?

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:

type OneOrRootTwo = 1 | typeof root2;

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:

const root2 = 1.4142135623730951 as const;
type OneOrRootTwo = 1 | typeof root2; // 1 | 1.4142135623730951

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:

const x: OneOrRootTwo = Math.SQRT2 as 1.4142135623730951;

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