TypeScript Code Formatter

TypeScript and TSX code formatting and beautification tool with syntax highlighting, error detection and custom formatting options

Format Options

Tool Overview: TypeScript Code Formatter

The TypeScript Code Formatter is a Prettier-powered professional online code beautifier specifically designed for formatting and beautifying TypeScript and TSX code. Using the industry-standard Prettier formatting engine ensures professional-grade code formatting and consistency. It supports syntax highlighting, error detection, and rich customizable formatting options to help developers improve code quality and readability.

What Is TypeScript Code Formatter?

TypeScript Code Formatter formats content with consistent indentation and layout for better readability.

How to Use

  1. Paste the content to format.
  2. Choose indentation and formatting options.
  3. Format and copy the output.

Common Use Cases

  • Normalize style before commit
  • Spot structure or syntax issues
  • Present clean snippets in docs

โ“ FAQ

Q1: Formatting failed?
A: Check the input syntax before formatting.

Q2: Can I minify?
A: Use a compact option if available.

Q3: Keep comments?
A: Choose a mode that preserves comments.

โœจ Key Features

  • ๐ŸŽจ Prettier-Powered: Uses the industry-standard Prettier formatting engine for professional-grade code formatting
  • ๐Ÿ” Syntax Validation: Real-time syntax error detection with detailed error information
  • โš™๏ธ Custom Options: Provides rich Prettier-compatible formatting configuration options
  • ๐Ÿ“ Syntax Highlighting: Clear code syntax highlighting display
  • ๐Ÿ“‹ Example Code: Built-in TypeScript and TSX example code
  • ๐Ÿ’พ Export Functions: Supports copying and downloading formatted code
  • ๐ŸŒ Multi-language Support: Supports Chinese, English and other language interfaces
  • ๐Ÿ“ฑ Responsive Design: Perfect adaptation for desktop and mobile devices
  • โšก High Performance: Based on mature Prettier library for fast and stable formatting

๐Ÿ“– Usage Guide

Basic Usage

  1. Input Code: Paste or enter your TypeScript/TSX code in the input box
  2. Configure Options: Adjust formatting options as needed
  3. Format Code: Click the "Format Code" button to beautify code
  4. Validate Syntax: Click the "Validate Syntax" button to check code syntax
  5. Copy Results: Use the copy button to get the formatted code

Formatting Options

Basic Options

  • Print Width: Set the maximum number of characters per line (40-200)
  • Tab Width: Set the width of tabs (1-8)
  • Use Tabs: Choose to use tabs or spaces for indentation

Syntax Options

  • Semicolons: Choose whether to add semicolons at the end of statements
  • Quote Type: Choose to use single or double quotes
  • JSX Quotes: Set quote type in JSX attributes
  • Trailing Comma: Set whether to add commas at the end of objects and arrays

Format Options

  • Bracket Spacing: Set whether to add spaces inside object literal brackets
  • JSX Bracket Same Line: Set whether JSX element closing brackets are on the same line as the last content
  • Arrow Function Parentheses: Set whether to add parentheses for single-parameter arrow functions

๐Ÿ”ง Formatting Configuration Details

Indentation Settings

// Using 2 spaces for indentation
interface User {
  id: number;
  name: string;
}

// Using tabs for indentation
interface User {
	id: number;
	name: string;
}

Semicolon Settings

// Always add semicolons
const user = { name: 'John' };
const getName = () => user.name;

// Never add semicolons
const user = { name: 'John' }
const getName = () => user.name

Quote Settings

// Using single quotes
const message = 'Hello, World!';
import { Component } from 'react';

// Using double quotes
const message = "Hello, World!";
import { Component } from "react";

Trailing Commas

// ES5 mode (objects and arrays)
const obj = {
  name: 'John',
  age: 30,
};

// All mode (including function parameters)
function greet(
  name: string,
  age: number,
) {
  return `Hello, ${name}!`;
}

๐Ÿ“‹ TypeScript Examples

Basic Types and Interfaces

// Basic types
let name: string = 'John';
let age: number = 30;
let isActive: boolean = true;

// Interface definition
interface User {
  id: number;
  name: string;
  email?: string;
  roles: string[];
}

// Type alias
type Status = 'pending' | 'approved' | 'rejected';

// Generic interface
interface ApiResponse<T> {
  data: T;
  status: number;
  message: string;
}

Classes and Inheritance

// Abstract class
abstract class Animal {
  protected name: string;
  
  constructor(name: string) {
    this.name = name;
  }
  
  abstract makeSound(): void;
  
  move(): void {
    console.log(`${this.name} is moving`);
  }
}

// Class inheritance
class Dog extends Animal {
  private breed: string;
  
  constructor(name: string, breed: string) {
    super(name);
    this.breed = breed;
  }
  
  makeSound(): void {
    console.log('Woof!');
  }
  
  getBreed(): string {
    return this.breed;
  }
}

Generics and Utility Types

// Generic function
function identity<T>(arg: T): T {
  return arg;
}

// Generic constraints
interface Lengthwise {
  length: number;
}

function loggingIdentity<T extends Lengthwise>(arg: T): T {
  console.log(arg.length);
  return arg;
}

// Utility types
interface User {
  id: number;
  name: string;
  email: string;
  password: string;
}

type PublicUser = Omit<User, 'password'>;
type UserUpdate = Partial<Pick<User, 'name' | 'email'>>;

๐Ÿš€ TSX Examples

React Components

import React, { useState, useEffect } from 'react';

// Component props interface
interface ButtonProps {
  variant: 'primary' | 'secondary' | 'danger';
  size?: 'small' | 'medium' | 'large';
  disabled?: boolean;
  onClick: (event: React.MouseEvent<HTMLButtonElement>) => void;
  children: React.ReactNode;
}

// Function component
const Button: React.FC<ButtonProps> = ({
  variant,
  size = 'medium',
  disabled = false,
  onClick,
  children
}) => {
  const className = `btn btn-${variant} btn-${size}`;
  
  return (
    <button
      className={className}
      disabled={disabled}
      onClick={onClick}
    >
      {children}
    </button>
  );
};

export default Button;

Hooks Usage

import React, { useState, useEffect, useCallback } from 'react';

interface User {
  id: number;
  name: string;
  email: string;
}

const UserList: React.FC = () => {
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);

  const fetchUsers = useCallback(async () => {
    try {
      setLoading(true);
      const response = await fetch('/api/users');
      
      if (!response.ok) {
        throw new Error('Failed to fetch users');
      }
      
      const userData: User[] = await response.json();
      setUsers(userData);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unknown error');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchUsers();
  }, [fetchUsers]);

  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error: {error}</div>;

  return (
    <div className="user-list">
      <h2>Users</h2>
      <ul>
        {users.map(user => (
          <li key={user.id}>
            <strong>{user.name}</strong> - {user.email}
          </li>
        ))}
      </ul>
    </div>
  );
};

export default UserList;

๐Ÿ’ก Best Practices

1. Code Organization

  • Use consistent indentation and formatting rules
  • Use type annotations appropriately to improve code readability
  • Follow naming conventions and use meaningful variable and function names

2. Type Safety

  • Avoid using the any type whenever possible
  • Use strict TypeScript configuration
  • Leverage utility types to improve type safety

3. Performance Optimization

  • Use generics appropriately to avoid type redundancy
  • Use const assertions to optimize type inference
  • Avoid overly complex type definitions

4. Team Collaboration

  • Establish unified code formatting standards
  • Use ESLint and Prettier for automated code checking
  • Conduct regular code reviews and refactoring

๐Ÿ” Common Issues

1. Formatting Failure

Problem: Error occurs during code formatting
Solution: Check if the code syntax is correct, fix syntax errors and reformat

2. Type Errors

Problem: TypeScript type checking fails
Solution: Carefully check type annotations to ensure type matching

3. JSX Syntax Issues

Problem: JSX syntax errors in TSX code
Solution: Ensure JSX elements are properly closed and attribute names are correct

๐Ÿ“š Related Resources


Note: This tool provides basic code formatting functionality. For complex projects, it's recommended to use professional IDEs and configuration files for code formatting.