Skip to main content

TypeScript Print

As a TypeScript developer, you're likely familiar with using console.log() to display information. However, printing to the console can be more intricate than it appears. Whether you're debugging or simply displaying data, TypeScript offers various methods for printing values, objects, and more. In this article, we'll discuss different techniques for printing in TypeScript, covering values, objects, formatted strings, arrays, error messages, JSON data, and variable types.

Printing Values and Objects

In TypeScript, printing values and objects to the console is a common task for debugging or logging.

Printing Values to the Console

For simple values, use console.log(), which is part of the Node.js API. Here’s how:

console.log('Hello, World!');

const name = 'John Doe';
console.log(name);

// Multiple values
const age = 30;
console.log('Name:', name, 'Age:', age);

When working with TypeScript print to console operations, you can leverage various formatting options to improve output readability. For more advanced patterns, Convex's TypeScript best practices provide insights on effective logging strategies.

Printing Object Properties

When dealing with objects, print specific properties using dot notation:

const person = { name: 'John Doe', age: 30, role: 'developer' };

// Specific properties
console.log(person.name); // Output: John Doe
console.log(person.age); // Output: 30

// Entire object
console.log(person); // Shows complete object structure

// Pretty-printed object
console.log(JSON.stringify(person, null, 2));

For complex nested object structures, consider using formatted output methods for better readability. When building real-time applications with Convex, you may need to debug complex data structures, making effective object printing crucial.

Formatting Strings and Printing Arrays

Besides printing basic values and objects, you might need to format strings or display arrays clearly.

Printing Formatted Strings

Use template literals for string formatting, which allow embedding expressions within strings:

const name = 'John Doe';
const age = 30;
const role = 'developer';

// Basic template literal
console.log(`My name is ${name} and I am ${age} years old.`);

// Multi-line formatting
console.log(`
User Profile:
- Name: ${name}
- Age: ${age}
- Role: ${role}
`);

Using TypeScript string interpolation with template literals makes code more readable than traditional string concatenation. For complex multi-line output, consider TypeScript multiline string techniques. These patterns align well with Convex's approach to code generation where clarity is paramount.

Printing Arrays Clearly

To make arrays readable, convert them to JSON strings with JSON.stringify():

const numbers = [1, 2, 3, 4, 5];
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
];

// Basic array output
console.log(numbers); // [1, 2, 3, 4, 5]

// Formatted array with JSON.stringify
console.log(JSON.stringify(numbers, null, 2));

// Pretty-printed complex arrays
console.log(JSON.stringify(users, null, 2));
/* Output:
[
{
"id": 1,
"name": "Alice"
},
{
"id": 2,
"name": "Bob"
}
]
*/

Working with TypeScript array structures becomes more manageable with proper formatting. When implementing complex filtering operations as described in Convex's guide to complex filters, well-formatted output aids debugging.

Printing Error Messages and JSON Data

Printing error messages and JSON data is vital for debugging and logging.

Printing Error Messages

Effective error handling includes clear error output:

function processData(data: unknown) {
try {
if (!data) {
throw new Error('No data provided');
}
// Process data...
} catch (error) {
if (error instanceof Error) {
console.error('Error:', error.message);
console.error('Stack trace:', error.stack);
} else {
console.error('Unknown error:', error);
}
}
}

// Custom error formatting
class ValidationError extends Error {
constructor(message: string, public field: string) {
super(message);
this.name = 'ValidationError';
}
}

try {
throw new ValidationError('Invalid email format', 'email');
} catch (error) {
if (error instanceof ValidationError) {
console.error(`Validation failed - Field: ${error.field}, Message: ${error.message}`);
}
}

Understanding the TypeScript Error type patterns helps create robust error handling. The try catch structure provides a foundation for error management, while catching the Error type ensures type safety in error handling.

Printing JSON Data

JSON formatting enhances data readability:

const userData = {
name: 'John Doe',
age: 30,
address: {
street: '123 Main St',
city: 'Anytown',
state: 'CA'
},
hobbies: ['reading', 'coding', 'hiking']
};

// Basic JSON output
console.log(JSON.stringify(userData));

// Pretty-printed JSON
console.log(JSON.stringify(userData, null, 2));

// Selective serialization with replacer
console.log(JSON.stringify(userData, ['name', 'age'], 2));

// Custom serialization
const serializer = (key: string, value: any) => {
if (key === 'age') return `${value} years`;
return value;
};
console.log(JSON.stringify(userData, serializer, 2));

Working with TypeScript JSON type definitions ensures type safety when handling JSON data. This approach aligns with Convex's TypeScript best practices for data handling in real-time applications.

Printing Variable Types for Debugging

Identifying and printing variable types is useful for debugging and data verification.

Printing Variable Types

Use the typeof operator to determine and print variable types:

const name = 'John Doe';
const age = 30;
const isActive = true;
const userData = { role: 'admin' };
const numbers = [1, 2, 3];

console.log(typeof name); // Output: string
console.log(typeof age); // Output: number
console.log(typeof isActive); // Output: boolean
console.log(typeof userData); // Output: object
console.log(typeof numbers); // Output: object

// More specific type checking
console.log(Array.isArray(numbers)); // Output: true
console.log(numbers instanceof Array); // Output: true

// Custom type checking function
function printDetailedType(value: any): void {
if (Array.isArray(value)) {
console.log('Type: Array');
} else if (value === null) {
console.log('Type: null');
} else if (value instanceof Date) {
console.log('Type: Date');
} else {
console.log(`Type: ${typeof value}`);
}
}

printDetailedType(numbers); // Output: Type: Array
printDetailedType(new Date()); // Output: Type: Date

Understanding TypeScript typeof operations helps identify runtime types during debugging. For comprehensive type system knowledge, explore TypeScript types patterns. When working withTypeScript data types, proper type checking ensures code reliability. These techniques become vital when implementing type-safe filtering patterns as described in Convex's complex filters guide.

Overcoming Common Challenges

TypeScript developers often face challenges when printing information or debugging. Here are some common issues and solutions:

Printing Complex Objects

When dealing with nested or complex objects, basic console.log() might not provide sufficient clarity:

const complexObject = {
name: 'John Doe',
address: {
street: '123 Main St',
city: 'Anytown',
state: 'CA',
zip: '12345'
},
metrics: {
performance: { cpu: 0.5, memory: 0.3 },
requests: { total: 1000, errors: 12 }
}
};

// Basic output can be confusing
console.log(complexObject);

// Better: formatted JSON output
console.log(JSON.stringify(complexObject, null, 2));

// Even better: custom formatting function
function printObject(obj: object, indent = 0) {
const spaces = ' '.repeat(indent);
for (const [key, value] of Object.entries(obj)) {
if (typeof value === 'object' && value !== null) {
console.log(`${spaces}${key}:`);
printObject(value, indent + 2);
} else {
console.log(`${spaces}${key}: ${value}`);
}
}
}

printObject(complexObject);

Formatting Strings for Output

Template literals are efficient for string formatting:

const user = { name: 'John', role: 'admin', lastLogin: new Date() };

// Basic template literal
console.log(`User: ${user.name} (${user.role})`);

// Advanced formatting with tagged templates
function styled(strings: TemplateStringsArray, ...values: any[]) {
return strings.reduce((acc, str, i) => {
const value = values[i] !== undefined ? values[i] : '';
return acc + str + (typeof value === 'object' ? JSON.stringify(value) : value);
}, '');
}

console.log(styled`User Data: ${user}`);

Debugging with Type Information

Type checking during runtime helps catch unexpected data:

function logWithType(value: any, label: string = '') {
const type = Array.isArray(value) ? 'array' :
value === null ? 'null' :
typeof value;

console.log(`${label}[${type}]: ${JSON.stringify(value, null, 2)}`);
}

// Usage examples
logWithType([1, 2, 3], 'Numbers');
logWithType({ key: 'value' }, 'Config');
logWithType(null, 'NullValue');

When implementing sophisticated type checking, typeof provides runtime type safety. For type-safe operations, explore TypeScript check type patterns.

These debugging techniques complement Convex's approach to complex filtering where proper data inspection is crucial for real-time applications.

Final Thoughts on Printing in TypeScript

Effective console output is essential for debugging and monitoring TypeScript applications. Understanding various printing techniques, from basic console.log() to complex object formatting, enables developers to diagnose issues quickly and build more maintainable applications.

By mastering these printing methods, you can:

  • Debug complex data structures efficiently
  • Format output for better readability
  • Type-check variables at runtime
  • Create clear, informative logs