Show Alerts in TypeScript

Recently, I was working on a TypeScript project that required displaying simple notification messages to users. The most straightforward approach was to use alert boxes.

Alerts are one of the simplest ways to show messages to users in web applications. They’re easy to implement and universally supported across browsers.

In this article, I’ll show you several ways to display alerts in TypeScript, from basic usage to more advanced implementations.

Basic Alert in TypeScript

The most straightforward way to show an alert in TypeScript is by using the built-in window.alert() method.

Here’s a simple example:

function showBasicAlert(): void {
  alert("This is a basic alert message!");
}

// Call the function
showBasicAlert();

This code displays a simple pop-up with the message “This is a basic alert message!” and an OK button.

The alert() function is actually a shorthand for window.alert(). Both work exactly the same way.

Creating Alert Functions with Parameters

Often, you’ll want to display different messages based on certain conditions. Here’s how to create a reusable alert function:

function showCustomAlert(message: string): void {
  alert(message);
}

// Usage examples
showCustomAlert("Your form has been submitted successfully!");
showCustomAlert("An error occurred. Please try again.");

This function accepts a string parameter and displays it in the alert box. It’s simple but very useful for different scenarios.

Displaying Dynamic Content in Alerts

Sometimes you need to show dynamic content in your alerts. Let’s see how we can incorporate variables:

function showDynamicAlert(username: string, score: number): void {
  alert(`Hello ${username}! Your current score is ${score}.`);
}

// Usage
showDynamicAlert("John", 85);

This will display: “Hello John! Your current score is 85.”

Template literals make it easy to include variables in your alert messages.

Confirmation Alerts with User Interaction

If you need the user to confirm an action, you can use the confirm() method:

import readline from 'readline';

function showConfirmationPrompt(): Promise<boolean> {
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });

  return new Promise((resolve) => {
    rl.question('Are you sure you want to delete this item? (y/n): ', (answer) => {
      rl.close();
      const confirmed = answer.trim().toLowerCase() === 'y';
      if (confirmed) {
        console.log('Item deleted successfully!');
      } else {
        console.log('Delete operation cancelled.');
      }
      resolve(confirmed);
    });
  });
}

// Usage
showConfirmationPrompt().then((confirmed) => {
  console.log('User confirmed:', confirmed);
});

Output:

Alert Message in TypeScript

The confirm() method returns a boolean value: true if the user selects “y” for yes, else it will return false.

Check out: Use Try Catch in TypeScript

Input Alerts with prompt()

If you need to collect some input from the user, the prompt() method is useful:

function getUserName(): string | null {
  const name = prompt("Please enter your name:", "Guest");

  if (name) {
    alert(`Hello, ${name}! Welcome to our website.`);
    return name;
  } else {
    alert("No name entered. Using default name.");
    return null;
  }
}

// Usage
const username = getUserName();
console.log("Username:", username);

The prompt() method returns the text entered by the user, or null if the user cancels the dialog.

Conditional Alerts Based on Application State

In real-world applications, you often need to show different alerts based on the application state:

enum UserRole {
  Admin = "admin",
  User = "user",
  Guest = "guest"
}

function showRoleBasedAlert(role: UserRole): void {
  switch(role) {
    case UserRole.Admin:
      alert("Welcome, Administrator! You have full access.");
      console.log("Welcome, Administrator! You have full access.");
       break;
    case UserRole.User:
      alert("Welcome back! You have standard user access.");
      console.log("Welcome back! You have standard user access.");
      break;
    case UserRole.Guest:
      alert("Welcome, Guest! You have limited access.");
      console.log("Welcome, Guest! You have limited access.");
      break;
    default:
      alert("Authentication required. Please log in.");
      console.log("Authentication required. Please log in.");
  }
}

// Usage
showRoleBasedAlert(UserRole.Admin);

Output:

Display alert in TypeScript

This function shows different alert messages depending on the user’s role.

Check out: Convert JSON to TypeScript Interface

Using Alert in Class-Based Components

If you’re working with class-based components in TypeScript, you can implement alerts as class methods:

class NotificationService {
  private userName: string;

  constructor(userName: string) {
    this.userName = userName;
  }

  public showWelcomeMessage(): void {
    alert(`Welcome back, ${this.userName}!`);
  }

  public showErrorMessage(errorCode: number): void {
    alert(`Error ${errorCode}: Something went wrong. Our team has been notified.`);
  }

  public showLogoutConfirmation(): boolean {
    return confirm("Are you sure you want to log out?");
  }
}

// Usage
const notifications = new NotificationService("Sarah");
notifications.showWelcomeMessage();

// Simulating an error
setTimeout(() => {
  notifications.showErrorMessage(404);
}, 3000);

// Confirming logout
function handleLogout(): void {
  const shouldLogout = notifications.showLogoutConfirmation();
  if (shouldLogout) {
    alert("You have been logged out successfully.");
    // Perform logout logic here
  }
}

Output:

Use Alerts in Class Based Components in TypeScript

This approach is helpful when building larger applications with multiple notification types.

Check out: Create an Object from an Interface in TypeScript

Creating Custom Alert Styling (Using Third-Party Libraries)

The standard JavaScript alerts are functional but quite basic in appearance. For more stylish alerts, you can use libraries like SweetAlert2 or AlertifyJS.

Here’s an example with SweetAlert2:

// You'll need to install SweetAlert2 first:
// npm install sweetalert2

import Swal from 'sweetalert2';

function showStylishAlert(): void {
  Swal.fire({
    title: 'Success!',
    text: 'Your profile has been updated.',
    icon: 'success',
    confirmButtonText: 'Great!'
  });
}

function showErrorAlert(errorMessage: string): void {
  Swal.fire({
    title: 'Error!',
    text: errorMessage,
    icon: 'error',
    confirmButtonText: 'Try Again'
  });
}

// Usage
showStylishAlert();

// Simulating an error scenario
setTimeout(() => {
  showErrorAlert("Unable to connect to the server. Please check your internet connection.");
}, 3000);

Output:

TypeScript Custom Alert messages

Third-party libraries offer more customization options compared to native alerts.

Using Alerts in TypeScript React Applications

If you’re working with React and TypeScript, you can create reusable alert components:

// AlertComponent.tsx
import React from 'react';

interface AlertProps {
  message: string;
  type: 'info' | 'success' | 'warning' | 'error';
  onClose?: () => void;
}

const AlertComponent: React.FC<AlertProps> = ({ message, type, onClose }) => {
  const getAlertStyle = (): React.CSSProperties => {
    const baseStyle: React.CSSProperties = {
      padding: '10px 15px',
      borderRadius: '4px',
      marginBottom: '15px',
      position: 'relative'
    };

    switch(type) {
      case 'success':
        return { ...baseStyle, backgroundColor: '#d4edda', color: '#155724' };
      case 'warning':
        return { ...baseStyle, backgroundColor: '#fff3cd', color: '#856404' };
      case 'error':
        return { ...baseStyle, backgroundColor: '#f8d7da', color: '#721c24' };
      default: // info
        return { ...baseStyle, backgroundColor: '#d1ecf1', color: '#0c5460' };
    }
  };

  return (
    <div style={getAlertStyle()}>
      {message}
      {onClose && (
        <button 
          onClick={onClose}
          style={{
            position: 'absolute',
            right: '10px',
            top: '10px',
            background: 'none',
            border: 'none',
            cursor: 'pointer'
          }}
        >
          ✕
        </button>
      )}
    </div>
  );
};

export default AlertComponent;

// Usage in another component
import React, { useState } from 'react';
import AlertComponent from './AlertComponent';

const App: React.FC = () => {
  const [showAlert, setShowAlert] = useState(false);
  const [alertMessage, setAlertMessage] = useState('');
  const [alertType, setAlertType] = useState<'info' | 'success' | 'warning' | 'error'>('info');

  const displayAlert = (message: string, type: 'info' | 'success' | 'warning' | 'error'): void => {
    setAlertMessage(message);
    setAlertType(type);
    setShowAlert(true);
  };

  return (
    <div>
      <h1>React TypeScript Alerts</h1>

      {showAlert && (
        <AlertComponent 
          message={alertMessage} 
          type={alertType} 
          onClose={() => setShowAlert(false)} 
        />
      )}

      <button onClick={() => displayAlert('Profile updated successfully!', 'success')}>
        Show Success Alert
      </button>

      <button onClick={() => displayAlert('Warning: You are about to delete your account', 'warning')}>
        Show Warning Alert
      </button>

      <button onClick={() => displayAlert('Error: Failed to save changes', 'error')}>
        Show Error Alert
      </button>
    </div>
  );
};

export default App;

This approach gives you much more control over the appearance and behavior of your alerts in a React application.

Check out: Use TypeScript Interface Array of Objects

Handling Alert Timing and Auto-Dismissal

Sometimes you want alerts to automatically disappear after a certain time period:

import { JSDOM } from 'jsdom';

// Set up jsdom for Node.js environment
const dom = new JSDOM('<!DOCTYPE html><body></body>');
const { document } = dom.window;
(global as any).document = document;

function showTimedAlert(message: string, duration: number = 3000): void {
  console.log(`showTimedAlert called with message: "${message}", duration: ${duration}ms`);
  alert(message);

  setTimeout(() => {
    console.log(`showTimedAlert: Alert closed after message: "${message}"`);
  }, duration);
}

function showCustomTimedAlert(message: string, duration: number = 3000): void {
  console.log(`showCustomTimedAlert called with message: "${message}", duration: ${duration}ms`);

  // Create alert element
  const alertEl = document.createElement('div');
  alertEl.textContent = message;
  alertEl.style.position = 'fixed';
  alertEl.style.top = '20px';
  alertEl.style.left = '50%';
  alertEl.style.transform = 'translateX(-50%)';
  alertEl.style.backgroundColor = '#333';
  alertEl.style.color = 'white';
  alertEl.style.padding = '10px 20px';
  alertEl.style.borderRadius = '4px';
  alertEl.style.zIndex = '9999';

  // Add to DOM
  console.log(`showCustomTimedAlert: Adding alert element to DOM`);
  document.body.appendChild(alertEl);

  // Remove after duration
  setTimeout(() => {
    console.log(`showCustomTimedAlert: Starting fade out for message: "${message}"`);
    alertEl.style.opacity = '0';
    alertEl.style.transition = 'opacity 0.5s';

    // Remove from DOM after fade out
    setTimeout(() => {
      console.log(`showCustomTimedAlert: Removing alert element from DOM for message: "${message}"`);
      document.body.removeChild(alertEl);
    }, 500);
  }, duration);
}

console.log('Initiating custom timed alert');
showCustomTimedAlert("Changes saved successfully!", 2000);

Output:

Handle Alert Timing in TypeScript

This custom approach gives you more flexibility for timed alerts compared to the native alert() function.

Check out: Check if an Object Implements an Interface in TypeScript

Best Practices for Using Alerts in TypeScript

After working with TypeScript alerts for years, I’ve developed some best practices that help create a better user experience:

  1. Use alerts sparingly: Excessive alerts can annoy users. Reserve them for important information or critical errors.
// Good practice - only show alerts for critical actions
function deleteAccount(userId: string): void {
  const isConfirmed = confirm("Warning: This will permanently delete your account and all associated data. This action cannot be undone. Continue?");

  if (isConfirmed) {
    // Proceed with deletion
    alert("Your account has been deleted successfully.");
  }
}
  1. Provide helpful information: Make your alert messages clear and actionable.
// Bad example
function showError(): void {
  alert("Error!");
}

// Good example
function showDetailedError(errorCode: number, operation: string): void {
  alert(`Error ${errorCode}: Unable to complete ${operation}. Please try again or contact support if the problem persists.`);
}
  1. Consider mobile users: Standard alerts can be disruptive on mobile devices. Consider using in-page notifications for less critical messages.
function showMobileFriendlyAlert(message: string): void {
  const isMobile = window.innerWidth <= 768;

  if (isMobile) {
    // Create an in-page notification instead of using alert()
    const notification = document.createElement('div');
    notification.textContent = message;
    notification.className = 'mobile-notification';
    document.body.appendChild(notification);

    // Auto-remove after 3 seconds
    setTimeout(() => {
      notification.classList.add('fade-out');
      setTimeout(() => document.body.removeChild(notification), 500);
    }, 3000);
  } else {
    // Use standard alert for desktop
    alert(message);
  }
}
  1. Provide type safety for your alert functions:
type AlertType = 'success' | 'info' | 'warning' | 'error';

interface AlertOptions {
  title?: string;
  message: string;
  type: AlertType;
  duration?: number;
}

function showTypedAlert(options: AlertOptions): void {
  const { title, message, type, duration = 3000 } = options;

  // Implementation depends on your UI framework or custom alert system
  console.log(`Showing ${type} alert: ${title ? title + ' - ' : ''}${message}`);
  alert(`${type.toUpperCase()}: ${title ? title + '\n' : ''}${message}`);
}

// Usage
showTypedAlert({
  title: 'Payment Processing',
  message: 'Your payment has been successfully processed.',
  type: 'success'
});

Output:

Type Safety in TypeScript Alerts
  1. Handle errors gracefully:
function fetchUserData(userId: string): Promise<void> {
  return fetch(`https://api.example.com/users/${userId}`)
    .then(response => {
      if (!response.ok) {
        throw new Error(`HTTP error! Status: ${response.status}`);
      }
      return response.json();
    })
    .then(data => {
      // Process data
      alert(`Welcome back, ${data.name}!`);
    })
    .catch(error => {
      console.error('Error fetching user data:', error);
      alert(`We encountered a problem loading your profile. Please refresh the page or try again later. (Error: ${error.message})`);
    });
}
  1. Consider using custom alert systems for consistent UX:
// Simple alert service
class AlertService {
  private static instance: AlertService;
  private containerElement: HTMLElement | null = null;

  private constructor() {
    // Create container for alerts if it doesn't exist
    if (!document.getElementById('alert-container')) {
      this.containerElement = document.createElement('div');
      this.containerElement.id = 'alert-container';
      this.containerElement.style.position = 'fixed';
      this.containerElement.style.top = '20px';
      this.containerElement.style.right = '20px';
      this.containerElement.style.zIndex = '9999';
      document.body.appendChild(this.containerElement);
    } else {
      this.containerElement = document.getElementById('alert-container');
    }
  }

  public static getInstance(): AlertService {
    if (!AlertService.instance) {
      AlertService.instance = new AlertService();
    }
    return AlertService.instance;
  }

  public show(message: string, type: AlertType = 'info', duration: number = 5000): void {
    const alertElement = document.createElement('div');
    alertElement.textContent = message;
    alertElement.className = `alert alert-${type}`;
    alertElement.style.marginBottom = '10px';
    alertElement.style.padding = '15px';
    alertElement.style.borderRadius = '4px';
    alertElement.style.boxShadow = '0 2px 5px rgba(0,0,0,0.2)';

    // Set background color based on type
    switch(type) {
      case 'success':
        alertElement.style.backgroundColor = '#d4edda';
        alertElement.style.color = '#155724';
        break;
      case 'warning':
        alertElement.style.backgroundColor = '#fff3cd';
        alertElement.style.color = '#856404';
        break;
      case 'error':
        alertElement.style.backgroundColor = '#f8d7da';
        alertElement.style.color = '#721c24';
        break;
      default: // info
        alertElement.style.backgroundColor = '#d1ecf1';
        alertElement.style.color = '#0c5460';
    }

    this.containerElement?.appendChild(alertElement);

    // Remove after duration
    setTimeout(() => {
      alertElement.style.opacity = '0';
      alertElement.style.transition = 'opacity 0.5s';

      // Remove from DOM after fade out
      setTimeout(() => {
        if (alertElement.parentNode === this.containerElement) {
          this.containerElement?.removeChild(alertElement);
        }
      }, 500);
    }, duration);
  }
}

// Usage
const alertService = AlertService.getInstance();
alertService.show('Your profile has been updated successfully!', 'success');
alertService.show('Please complete your profile information.', 'info');
alertService.show('Your session will expire in 5 minutes.', 'warning');
alertService.show('Failed to save changes. Please try again.', 'error');

Real-World Example: E-commerce Cart Alert System

Let’s look at a practical example for an e-commerce site that shows different alerts based on shopping cart actions:

interface Product {
  id: string;
  name: string;
  price: number;
  stockQuantity: number;
}

class ShoppingCart {
  private items: Map<string, number> = new Map(); // product ID -> quantity

  public addItem(product: Product, quantity: number = 1): void {
    if (product.stockQuantity < quantity) {
      alert(`Sorry, we only have ${product.stockQuantity} units of "${product.name}" in stock.`);
      return;
    }

    const currentQuantity = this.items.get(product.id) || 0;
    this.items.set(product.id, currentQuantity + quantity);

    alert(`Added ${quantity} ${quantity === 1 ? 'unit' : 'units'} of "${product.name}" to your cart.`);
  }

  public removeItem(productId: string): void {
    if (!this.items.has(productId)) {
      alert("This item is not in your cart.");
      return;
    }

    this.items.delete(productId);
    alert("Item removed from your cart.");
  }

  public checkout(): void {
    if (this.items.size === 0) {
      alert("Your cart is empty. Please add items before checking out.");
      return;
    }

    const isConfirmed = confirm("Ready to complete your purchase?");

    if (isConfirmed) {
      // Process payment logic would go here
      alert("Thank you for your purchase! Your order has been confirmed.");
      this.items.clear();
    }
  }

  public getItemCount(): number {
    let count = 0;
    this.items.forEach(quantity => {
      count += quantity;
    });
    return count;
  }
}

// Usage example
const macbook = {
  id: "laptop-001",
  name: "MacBook Pro 16-inch",
  price: 2399.99,
  stockQuantity: 10
};

const airpods = {
  id: "audio-003",
  name: "AirPods Pro",
  price: 249.99,
  stockQuantity: 25
};

const cart = new ShoppingCart();
cart.addItem(macbook); // "Added 1 unit of "MacBook Pro 16-inch" to your cart."
cart.addItem(airpods, 2); // "Added 2 units of "AirPods Pro" to your cart."

// Try to add more than available
cart.addItem(macbook, 15); // "Sorry, we only have 10 units of "MacBook Pro 16-inch" in stock."

// Checkout process
cart.checkout(); // Confirms purchase and shows thank you message

Output:

Create alert Message in TypeScript

Check out: Set Default Values for TypeScript Types

Conclusion

In this TypeScript tutorial, we have learned how to use alerts in TypeScript applications to display alert messages to the users. While standard TypeScript alerts are simple, they lack styling flexibility. For a better user experience, custom alert components or third-party libraries are recommended.

Properly implemented alerts guide users and prevent errors. By following the above methods, you can choose alert methods that align with your TypeScript application’s needs.

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.