Sling Academy
Home/TypeScript/TypeScript: Force Positive Number with ‘+’ Sign

TypeScript: Force Positive Number with ‘+’ Sign

Last updated: January 08, 2024

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.

Next Article: TypeScript: Force Negative Number with ‘-‘ Sign

Previous Article: TypeScript: How to Check if a String is Empty

Series: The First Steps to TypeScript

TypeScript

You May Also Like

  • TypeScript: setInterval() and clearInterval() methods (3 examples)
  • TypeScript sessionStorage: CRUD example
  • Using setTimeout() method with TypeScript (practical examples)
  • Working with window.navigator object in TypeScript
  • TypeScript: Scrolling to a specific location
  • How to resize the current window in TypeScript
  • TypeScript: Checking if an element is a descendant of another element
  • TypeScript: Get the first/last child node of an element
  • TypeScript window.getComputerStyle() method (with examples)
  • Using element.classList.toggle() method in TypeScript (with examples)
  • TypeScript element.classList.remove() method (with examples)
  • TypeScript: Adding Multiple Classes to An Element
  • element.insertAdjacentHTML() method in TypeScript
  • TypeScript – element.innerHTML and element.textContent
  • Using element.removeAttribute() method in TypeScript
  • Working with Document.createElement() in TypeScript
  • Using getElementById() method in TypeScript
  • Using Window prompt() method with TypeScript
  • TypeScript – window.performance.measure() method (with examples)