Cannot create type as specific number when number is in variable

  javascript, math, node.js, typescript, variables

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?

Source: Ask Javascript Questions

LEAVE A COMMENT