TypeScript: Force Positive Number with ‘+’ Sign

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

Introduction

TypeScript’s type system allows for precise control over typing, lending itself to a robust and predictable codebase. This tutorial discusses how to enforce the representation of positive numbers with a ‘+’ sign.

Understanding TypeScript’s Type System

Before diving into the specifics of forcing the ‘+’ sign before positive numbers, it’s vital to understand the type system of TypeScript. TypeScript extends JavaScript by adding types to the language. This means that variables, parameters, and return types can be explicitly typed, resulting in more predictable and easier-to-maintain code.

Literal Types and Template Literal Types

One powerful feature in TypeScript is the ability to use literal types. This means you can specify the exact value a variable must hold, and in our case, the exact string representation of a number. TypeScript 4.1 introduced template literal types, which take this a step further by allowing string literal types to be constructed by joining strings together, creating the potential for enforcing formatting rules in string types.

Basic Usage of Literal Types for Positive Numbers

To demonstrate the concept of enforcing the ‘+’ sign, let’s start with a simple use case.

function formatPositiveNumber(num: number): string {
  return num > 0 ? `+${num}` : num.toString();
}

console.log(formatPositiveNumber(5)); // Outputs: '+5'
console.log(formatPositiveNumber(-2)); // Outputs: '-2'

Advanced Typing for Enforcing Format

For literals that need to always display a ‘+’ sign, we can use a custom type that leverages template strings.

type PositiveNumberWithSign = `+${number}`;

function formatPositiveNumberAdvanced(num: number): PositiveNumberWithSign | string {
  if (num > 0) {
    const formatted: PositiveNumberWithSign = `+${num}` as PositiveNumberWithSign;
    return formatted;
  }
  return num.toString();
}

Validating Output

To ensure the output of your functions adheres to the formatting rules, consider using a type guard that performs runtime checks.

function isPositiveNumberWithSign(value: string): value is PositiveNumberWithSign {
  return /^[+][0-9]+$/.test(value);
}

Conclusion

In conclusion, TypeScript provides the tools to enforce strict typing and formatting within your codebase, including the representation of positive numbers with a ‘+’ sign. By utilizing literal types and the concept of template literals, we can introduce a layer of type safety that further leverages TypeScript’s capabilities for accurate and self-documenting code.