TypeScript: Force Negative Number with ‘-‘ Sign

Updated: January 8, 2024 By: Guest Contributor Post a comment

Overview

TypeScript, as a superset of JavaScript, inherits its rules for negatives, but our type-strong alley allows us to enforce negative values explicitly. Herein, we delve into the art of ensuring numbers bear the ‘-‘ sign truly.

Ensuring Negativity

Where the intention is to depict a deficit, TypeScript does not balk; it embraces the ‘-‘ sign with Edison’s keenness. To start a’ simple, observe the following:

let debt: number = -48;
console.log(debt); // Output: -48

Similarly, one might wish to transform a possibly positive number to its surly counterpart:


function ensureNegative(num: number): number {
  return num < 0 ? num : -num;
}

const value: number = ensureNegative(42);
console.log(value); // Output: -42

Typing the Grumpy Integer

As the tale goes, typings are there to guide the typesetter. Let us consider an exclusive type for these grumpy integers:


type NegativeNumber = number &amp; {
  __negative__: never;
};

function toNegative(num: number): NegativeNumber {
  if (num < 0) {
    return num as NegativeNumber;
  }
  throw new Error("That is not a negative number!");
}

const deficit: NegativeNumber = toNegative(-30);
console.log(deficit); // Ouput: -30

And what if our number is concealed within a string, akin to the disguise of the Prince and the Pauper? TypeScript, wielding the parse with precision, uncovers the truth:


const numeral: string = "-102";
const expense: number = parseInt(numeral, 10);
console.log(expense); // Output: -102

Crafting Negatives with Generics

The advanced practitioner might choose to sojourn in the realm of generics whilst enforcing negative numbers:


function forceNegative(num: T): NegativeNumber {
  return (num > 0 ? -num : num) as NegativeNumber;
}

// Usage with literal type
const loss: NegativeNumber = forceNegative(-5);
console.log(loss); // Output: -5

In the case of a battalion of numbers, a union of types is employed, bringing out the negative cohorts:


function filterNegative(numbers: number[]): NegativeNumber[] {
  return numbers.filter((num) => num < 0) as NegativeNumber[];
}

const mixture: number[] = [4, -1, -24, 67];
const debts: NegativeNumber[] = filterNegative(mixture);
console.log(debts); // Output: [-1, -24]

Conclusion

In the grand story that is TypeScript, enforcing a ‘-‘ symbol on numbers is akin to Twain’s own navigation of the Mississippi—intricate, but doable. Through typings and functions, we’ve forged our negative numbers with intention, and like a skilled pilot avoids the shoals and snags, we artfully avoid the positive…