How to Print in TypeScript: Different Ways to Display Output

When I first started working with TypeScript, one of the most basic yet essential things I needed to figure out was how to print or display output.

Whether for debugging, logging, or user interaction, printing values is a fundamental skill every TypeScript developer needs.

In this article, I’ll show you several different ways to print output in TypeScript, from console methods to DOM manipulation. I’ll cover approaches for both Node.js and browser environments, providing practical examples that you can start using immediately.

Understanding TypeScript Print Output Methods in TypeScript

TypeScript, being a superset of JavaScript, inherits all of JavaScript’s printing capabilities. However, the method you choose depends on your environment and specific requirements.

Let’s explore the various ways to display output in TypeScript.

Method 1: Using console.log() in TypeScript

The most common and straightforward way to print in TypeScript is using the console.log() method.

// Basic usage
console.log("Hello from TypeScript!");

// Printing variables
const userName: string = "Sarah";
const userAge: number = 28;
console.log("User:", userName, "Age:", userAge);

// String interpolation
console.log(`${userName} is ${userAge} years old.`);

// Printing objects
const user = {
  name: "John Smith",
  location: "New York",
  isActive: true
};
console.log(user);

This method works in both Node.js and browser environments. It’s my go-to choice for quick debugging or development purposes.

Print in TypeScript

Method 2: Other Console Methods in TypeScript

The console object offers several specialized methods beyond just log():

// Warning message (usually appears in yellow)
console.warn("This is a warning message");

// Error message (usually appears in red)
console.error("This is an error message");

// Informational message (may be styled differently in some browsers)
console.info("This is an informational message");

// Table format for arrays and objects
const users = [
  { name: "Alice", city: "Chicago", age: 32 },
  { name: "Bob", city: "Boston", age: 45 },
  { name: "Carol", city: "Denver", age: 27 }
];
console.table(users);

I often use these specialized methods to make different types of output more distinguishable, especially in complex applications.

Print Output using Console method in TypeScript

Method 3: Using process.stdout in Node.js

If you’re working in a Node.js environment, you can use process.stdout.write() for more control over your output:

// Basic usage without automatic newline
process.stdout.write("Hello ");
process.stdout.write("World\n");

// Creating a simple progress indicator
function showProgress(percent: number): void {
  process.stdout.clearLine(0);
  process.stdout.cursorTo(0);
  process.stdout.write(`Loading: ${percent}%`);
}

// Usage example (simulating progress)
for (let i = 0; i <= 100; i += 10) {
  setTimeout(() => showProgress(i), i * 50);
}

This method is particularly useful for command-line interfaces or when precise control over output formatting is required.

process stdout in Node.js in TypeScript

Method 4: DOM Manipulation in Browser Environments

When working in a browser, you can print directly to the HTML document:

// Adding text to an element
document.getElementById("output")!.textContent = "Hello from TypeScript!";

// Creating and appending new elements
function printMessage(message: string): void {
  const outputDiv = document.getElementById("output");
  const messageElement = document.createElement("p");
  messageElement.textContent = message;
  outputDiv?.appendChild(messageElement);
}

// Usage
printMessage("First message");
printMessage("Second message");

I use this approach when I need to display output directly to users in web applications.

DOM Manipulation in Browser Environments in TypeScript

Method 5: Using Template Strings for Formatted Output in TypeScript

Template strings offer a clean way to format complex output:

const product = {
  name: "Smartphone",
  price: 799.99,
  inStock: true
};

const formattedOutput = `
Product: ${product.name}
Price: $${product.price.toFixed(2)}
Available: ${product.inStock ? "Yes" : "No"}
`;

console.log(formattedOutput);

This approach is excellent for creating readable multi-line output with dynamic values.

Use Template Strings for Formatted Output in TypeScript

Method 6: Using console.group() for Structured Output in TypeScript

For complex debugging, organizing related logs can be helpful:

function processOrder(orderId: string, items: string[]): void {
  console.group(`Order Processing: ${orderId}`);

  console.log("Started processing");
  console.log(`Items: ${items.join(", ")}`);

  console.group("Validation");
  console.log("Checking inventory...");
  console.log("Verifying payment...");
  console.groupEnd();

  console.log("Order completed");
  console.groupEnd();
}

// Usage
processOrder("ORD-12345", ["Laptop", "Mouse", "Keyboard"]);

This creates a collapsible hierarchy in the console, which is incredibly useful for tracking complex processes.

Use console group() for Structured Output in TypeScript

Method 7: Custom Print Functions in TypeScript

Creating your own print utility can help standardize output across your application:

// Custom print function with timestamps and categories
function customPrint(message: string, category: 'info' | 'warning' | 'error' = 'info'): void {
  const timestamp = new Date().toISOString();
  const prefix = `[${timestamp}] [${category.toUpperCase()}]`;

  switch (category) {
    case 'warning':
      console.warn(`${prefix} ${message}`);
      break;
    case 'error':
      console.error(`${prefix} ${message}`);
      break;
    default:
      console.log(`${prefix} ${message}`);
  }
}

// Usage
customPrint("Application started");
customPrint("Configuration file missing", "warning");
customPrint("Failed to connect to database", "error");

I’ve found custom print functions like this invaluable for maintaining consistent logging patterns across larger applications.

Custom Print Functions in TypeScript

Performance Considerations in TypeScript

While printing is essential for development, excessive logging can impact performance, especially in production environments. I recommend:

  1. Using conditional logging in production code
  2. Removing or disabling verbose logs before deployment
  3. Considering a structured logging library for production applications
// Environment-aware logging
const isDevelopment = process.env.NODE_ENV === 'development';

function debugLog(message: string): void {
  if (isDevelopment) {
    console.log(`[DEBUG] ${message}`);
  }
}

// Usage
debugLog("This will only show in development");

Conclusion

I hope you found this guide helpful for understanding the various ways to print output in TypeScript. From simple console logs to complex formatted output, these methods cover most scenarios you’ll encounter in TypeScript development.

Remember that the right printing method depends on your specific use case – whether you’re debugging during development, creating user interfaces, or building command-line tools. Choose the approach that best fits your needs, and your code will be more readable and maintainable.

Other TypeScript articles you may also like:

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.