πŸ“˜

TypeScript Formatter

Format and beautify TypeScript code with proper indentation, spacing, and line breaks. Preserves type annotations, interfaces, generics, and all TypeScript-specific syntax.

Developer Tools
Loading tool...

How to Use TypeScript Formatter

Quick Start Guide

  1. Paste Code: Copy your unformatted or messy TypeScript code into the input area
  2. Configure Options: Choose indentation, quotes, semicolons, and other formatting preferences
  3. Format: Click "Format Code" to beautify your TypeScript
  4. Copy or Download: Use the output buttons to copy or download the formatted code
  5. Try Examples: Click example buttons to see different TypeScript formatting scenarios

What is TypeScript Formatting?

TypeScript formatting (also called beautification or pretty-printing) transforms unformatted, messy, or inconsistent TypeScript code into clean, human-readable code with proper indentation, spacing, and line breaks while preserving all type annotations, interfaces, generics, and TypeScript-specific features.

Purpose: Code readability, maintaining style consistency, team collaboration Input: Unformatted, messy, or inconsistent TypeScript code Output: Clean, properly indented, readable TypeScript code Usage: Development, code review, learning, documentation

Why Format TypeScript?

Development Benefits:

  • Standardize TypeScript code style across your team
  • Make complex type definitions more readable
  • Improve code review efficiency and quality
  • Maintain consistent style in large TypeScript projects
  • Learn from well-formatted TypeScript examples
  • Clean up automatically generated or copied code

Common Scenarios:

  • Formatting code from online sources or Stack Overflow
  • Cleaning up legacy TypeScript codebases
  • Standardizing code before commits
  • Preparing code for documentation
  • Making complex interfaces and types readable
  • Teaching and learning TypeScript

TypeScript-Specific Features

Fully Preserved:

  • Type annotations (: string, : number, etc.)
  • Interface definitions
  • Type aliases and unions
  • Generic type parameters (<T>, <T extends U>)
  • Enum declarations
  • Access modifiers (public, private, protected)
  • Readonly properties
  • Optional properties (?)
  • Non-null assertions (!)
  • Type assertions (as Type, <Type>)

Formatting Options Explained

Indentation

Indent Size:

  • 2 spaces: Modern TypeScript standard (Prettier, Microsoft)
  • 4 spaces: Traditional preference, more visual separation
  • Tabs: Flexible, allows individual developer preferences

Indent Type:

  • Spaces: Consistent across all editors and viewers
  • Tabs: More efficient, customizable display width

When to use:

  • 2 spaces: Modern web projects, Angular, React with TypeScript
  • 4 spaces: Enterprise projects, .NET conventions
  • Tabs: Team preference, accessibility considerations

Semicolons

Options:

  • Keep as-is: Preserve original semicolon usage
  • Add missing: Insert semicolons where they're implied (ASI)
  • Remove all: Remove all semicolons (modern style)

Examples:

// Keep as-is (preserves original)
const x: number = 5;
const y: string = "hello"

// Add missing
const x: number = 5;
const y: string = "hello";

// Remove all
const x: number = 5
const y: string = "hello"

Recommendation: Use "Add missing" for safety, matches TypeScript team style

Quotes

Options:

  • Keep as-is: Preserve original quote style
  • Single quotes: Convert to 'single quotes' (most popular)
  • Double quotes: Convert to "double quotes" (TypeScript default)

Examples:

// Single quotes
const name: string = 'John'
const greeting: string = 'Hello, World!'

// Double quotes
const name: string = "John"
const greeting: string = "Hello, World!"

Recommendation: Single quotes for consistency, double quotes matches official docs

Trailing Commas

Options:

  • None: No trailing commas
  • ES5: Add to arrays and objects only
  • All: Add to all multi-line structures (including function params and generics)

Examples:

// None
interface User {
  name: string
  email: string
}

// ES5 (objects and arrays)
interface User {
  name: string,
  email: string,
}

// All (including type parameters)
function map<
  T,
  U,
>(items: T[], fn: (item: T) => U): U[] {
  return items.map(fn)
}

Recommendation: ES5 for broad compatibility, All for modern TypeScript projects

Arrow Function Parentheses

Options:

  • Avoid: Omit parens for single parameters: x => x * 2
  • Always: Always use parens: (x) => x * 2

Examples:

// Avoid (cleaner for single params)
const double = (x: number) => x * 2  // Parens required due to type annotation
const names = users.map(u => u.name)

// Always (consistent style)
const double = (x: number) => x * 2
const names = users.map((u) => u.name)

Recommendation: Avoid for cleaner code, Always for consistency

Common Use Cases

1. Formatting Interface Definitions

Purpose: Make complex TypeScript interfaces readable

Before:

interface User{
name:string;
email:string;
age?:number;
address:{
street:string;
city:string;
country:string
};
roles:string[];
createdAt:Date
}

After (formatted with 2-space indent):

interface User {
  name: string;
  email: string;
  age?: number;
  address: {
    street: string;
    city: string;
    country: string;
  };
  roles: string[];
  createdAt: Date;
}

2. Formatting Generic Functions

Purpose: Clean up complex generic type parameters

Before:

function merge<
T extends object,
U extends object
>(
obj1:T,
obj2:U
):T&U{
return{
...obj1,
...obj2
}
}

function getProperty<
T,
K extends keyof T
>(
obj:T,
key:K
):T[K]{
return obj[key]
}

After:

function merge<T extends object, U extends object>(
  obj1: T,
  obj2: U
): T & U {
  return { ...obj1, ...obj2 }
}

function getProperty<T, K extends keyof T>(
  obj: T,
  key: K
): T[K] {
  return obj[key]
}

3. Formatting TypeScript Classes

Purpose: Clean up class definitions with type annotations

Before:

class UserService{
private users:User[]=[];
constructor(
private readonly db:Database
){}
async getUser(
id:string
):Promise<User|null>{
const user=await this.db
.findOne(id);
return user;
}
public addUser(
user:User
):void{
this.users.push(user);
}
}

After:

class UserService {
  private users: User[] = [];

  constructor(private readonly db: Database) {}

  async getUser(id: string): Promise<User | null> {
    const user = await this.db.findOne(id);
    return user;
  }

  public addUser(user: User): void {
    this.users.push(user);
  }
}

4. Formatting Complex Type Definitions

Purpose: Make union, intersection, and conditional types readable

Before:

type Loading={
state:"loading"
};
type Success<T>={
state:"success";
data:T
};
type Error={
state:"error";
error:string
};
type ApiState<T>=
Loading|Success<T>|Error;

type NonNullable<T>=
T extends null|undefined
?never:T;

After:

type Loading = {
  state: "loading";
};

type Success<T> = {
  state: "success";
  data: T;
};

type Error = {
  state: "error";
  error: string;
};

type ApiState<T> = Loading | Success<T> | Error;

type NonNullable<T> = T extends null | undefined ? never : T;

5. Formatting React TypeScript Components

Purpose: Clean up React component code with TypeScript props

Before:

import React,{
useState
}from 'react';

interface ButtonProps{
label:string;
onClick:()=>void;
variant?:
"primary"|"secondary";
disabled?:boolean
}

const Button:
React.FC<ButtonProps>=({
label,
onClick,
variant="primary",
disabled=false
})=>{
const[count,setCount]=
useState<number>(0);

return <button
onClick={onClick}
disabled={disabled}>
{label}
</button>
};

After:

import React, { useState } from 'react';

interface ButtonProps {
  label: string;
  onClick: () => void;
  variant?: "primary" | "secondary";
  disabled?: boolean;
}

const Button: React.FC<ButtonProps> = ({
  label,
  onClick,
  variant = "primary",
  disabled = false
}) => {
  const [count, setCount] = useState<number>(0);

  return (
    <button onClick={onClick} disabled={disabled}>
      {label}
    </button>
  );
};

6. Formatting Enum Definitions

Purpose: Make enum declarations more readable

Before:

enum Status{Pending="PENDING",Active="ACTIVE",Inactive="INACTIVE",Deleted="DELETED"}const Colors={Red:"#ff0000",Green:"#00ff00",Blue:"#0000ff"}as const;type Color=typeof Colors[keyof typeof Colors];

After:

enum Status {
  Pending = "PENDING",
  Active = "ACTIVE",
  Inactive = "INACTIVE",
  Deleted = "DELETED"
}

const Colors = {
  Red: "#ff0000",
  Green: "#00ff00",
  Blue: "#0000ff"
} as const;

type Color = typeof Colors[keyof typeof Colors];

Features

Core Functionality

  • Automatic Indentation: Properly indent nested blocks, functions, and type definitions
  • Spacing Normalization: Add consistent spacing around operators and type annotations
  • Line Break Management: Insert line breaks for readability
  • Type Preservation: Keep all type annotations, interfaces, and generics intact
  • Comment Preservation: Maintain all comments (single-line and multi-line)
  • String Safety: Never modify content inside strings or template literals
  • Multiple Format Options: Customize to match your style guide

Supported TypeScript Features

Type System:

  • Type annotations (: Type)
  • Interface declarations
  • Type aliases (type Name = ...)
  • Union types (A | B)
  • Intersection types (A & B)
  • Generic type parameters (<T>, <T extends U>)
  • Conditional types (T extends U ? X : Y)
  • Mapped types ({ [K in keyof T]: ... })
  • Type assertions (as Type, <Type>)

OOP Features:

  • Classes with type annotations
  • Access modifiers (public, private, protected)
  • Abstract classes and methods
  • Readonly properties
  • Optional properties (?)
  • Parameter properties
  • Decorators (preserved)

Modern TypeScript:

  • Async/await with Promise types
  • Template literal types
  • Const assertions (as const)
  • Non-null assertions (!)
  • Definitely assigned assertions (!)
  • Tuple types
  • Enum declarations

Formatting Controls

Indentation:

  • 2 spaces (default, most popular)
  • 4 spaces (traditional)
  • Tabs (flexible)

Quote Style:

  • Keep original (default)
  • Single quotes (popular)
  • Double quotes (TypeScript docs)

Semicolons:

  • Keep as-is (preserve original)
  • Add missing (safe, explicit)
  • Remove all (modern, clean)

Trailing Commas:

  • None (minimal)
  • ES5 (arrays/objects)
  • All (including functions and generics)

Arrow Functions:

  • Avoid parens when possible
  • Always use parens (consistent)

Best Practices

1. Choose Team-Consistent Settings

Pick formatting options that match your TypeScript style guide:

Microsoft/TypeScript Team Style:

  • Indent: 4 spaces
  • Quotes: Double
  • Semicolons: Add
  • Trailing comma: ES5
  • Arrow parens: Avoid

Angular Style Guide:

  • Indent: 2 spaces
  • Quotes: Single
  • Semicolons: Add
  • Trailing comma: All
  • Arrow parens: Always

Prettier Default (TypeScript):

  • Indent: 2 spaces
  • Quotes: Double (for TS, configurable)
  • Semicolons: Add
  • Trailing comma: ES5
  • Arrow parens: Always

2. Format Before Committing

Workflow:

  1. Write your TypeScript code
  2. Format before committing
  3. Run type checker (tsc --noEmit)
  4. Run tests
  5. Commit formatted code

3. Combine with TSLint/ESLint

For best results:

  1. Format code first (this tool or Prettier)
  2. Run ESLint with TypeScript plugin
  3. Fix any linting issues
  4. Run type checker
  5. Commit

4. Use for Learning TypeScript

When studying TypeScript:

  1. Find code examples online
  2. Format them for better readability
  3. Study the structure and patterns
  4. Experiment with the code
  5. Learn TypeScript best practices

5. Document Your Style

For teams:

  • Document preferred formatting settings
  • Add to project README
  • Include .editorconfig file
  • Consider .prettierrc for automation
  • Use pre-commit hooks

Technical Details

How TypeScript Formatting Works

1. Parse input code character by character
2. Track context (strings, comments, type annotations)
3. Identify blocks, interfaces, and nesting levels
4. Apply indentation based on nesting
5. Add spacing around operators and colons
6. Handle TypeScript-specific syntax (generics, types)
7. Insert line breaks at appropriate points
8. Apply quote and semicolon preferences
9. Output formatted code with preserved types

Limitations

This is a basic formatter:

  • Uses character-by-character parsing (not full AST)
  • May not handle all edge cases perfectly
  • Works well for most common TypeScript patterns
  • Not a replacement for Prettier or TSLint

For production projects, consider:

  • Prettier: Full AST-based formatting with TypeScript support
  • ESLint + @typescript-eslint: Linting + auto-fixing
  • dprint: Fast, configurable TypeScript formatter
  • TypeScript Compiler: Built-in formatting APIs

This tool is best for:

  • Quick one-off formatting
  • Learning and education
  • Formatting code snippets
  • Simple formatting tasks
  • Privacy-focused formatting (100% local)

Supported Syntax

βœ… Fully supported:

  • Type annotations and type aliases
  • Interface and class declarations
  • Generic type parameters
  • Function signatures with types
  • Enum declarations
  • Union and intersection types
  • Arrow functions with types
  • Async functions with Promise types
  • Import/export with types
  • Const assertions

⚠️ Limited support:

  • Very complex mapped types
  • Deeply nested generic constraints
  • Complex conditional types
  • Template literal types (basic only)
  • Advanced decorator patterns

Performance

Processing speed:

  • Small files (<10KB): Instant
  • Medium files (10-100KB): <1 second
  • Large files (100KB-500KB): 1-2 seconds
  • Type definition files (.d.ts): Usually fast

Browser-based:

  • All processing in your browser
  • No server uploads or network delays
  • Works offline after initial load
  • RAM usage: ~2-5MB per 100KB

Troubleshooting

Issue: Type annotations look wrong

Possible causes:

  1. Complex generic syntax not fully parsed
  2. Angle brackets confused with comparison operators
  3. Edge case in type parsing

Solutions:

  • Verify original code has valid syntax
  • Try different formatting options
  • For complex types, use Prettier
  • Report specific issues with examples

Issue: Generics formatted incorrectly

Problem: Generic type parameters <T> might be treated as operators

Solutions:

  • Check input code syntax
  • Use Prettier for complex generics
  • Format in smaller sections
  • Keep type parameters simple when possible

Issue: Code doesn't type-check after formatting

This shouldn't happen - formatting should never affect types

If it does:

  1. Original code likely had type errors
  2. Compare formatted code with original
  3. Run tsc --noEmit to verify types
  4. Report issue with example

Browser Compatibility

Supported browsers:

  • βœ… Chrome 90+ (recommended)
  • βœ… Firefox 88+
  • βœ… Safari 14+
  • βœ… Edge 90+
  • βœ… Opera 76+

Required features:

  • ES6+ JavaScript support
  • Clipboard API (for copy)
  • Blob API (for download)
  • Modern CSS (for UI)

Works on:

  • Desktop: Windows, macOS, Linux
  • Mobile: iOS Safari, Chrome Android
  • Tablets: iPad, Android tablets

Privacy & Security

Client-Side Processing

  • 100% Local: All formatting in your browser
  • No Uploads: Code never sent to any server
  • No Storage: Nothing saved or cached
  • No Tracking: No analytics on your code
  • No Accounts: No login required

Security Features

  • Sandboxed: Runs in browser security sandbox
  • No Execution: Code never executed, only parsed
  • Safe Parsing: Character-based, not eval-based
  • No External Calls: No network requests during processing

Safe for Sensitive Code

  • βœ… Proprietary TypeScript code
  • βœ… Client projects with types
  • βœ… Internal type definitions
  • βœ… Code with business logic
  • βœ… Personal projects

Important: Remove API keys, passwords, and secrets before formatting, just like before committing to version control.

Comparison with Other Tools

TypeScript Formatter vs Prettier

TypeScript Formatter (this tool):

  • βœ… Browser-based, instant access
  • βœ… Simple, straightforward options
  • βœ… No installation required
  • βœ… Privacy-focused (100% local)
  • ❌ Basic parsing, not AST-based
  • ❌ Limited advanced features

Prettier:

  • βœ… Full AST parsing, perfect TypeScript support
  • βœ… Supports many languages
  • βœ… Widely used in production
  • βœ… Advanced TypeScript formatting
  • ❌ Requires npm installation
  • ❌ Opinionated (fewer options)

When to use this tool: Quick formatting, learning, one-off tasks, privacy needs

When to use Prettier: Production projects, team collaboration, automated formatting

TypeScript Formatter vs TSLint/ESLint

This tool: Formatting only TSLint/ESLint: Code quality checking + formatting

Use ESLint when: You want to catch bugs and enforce TypeScript best practices Use this tool when: You just need to format code quickly

Integration Tips

Using Formatted Code in Projects

1. Copy to Editor:

  • Format your TypeScript code
  • Click "Copy Output"
  • Paste into your IDE/editor
  • Run type checker to verify

2. Download File:

  • Format code
  • Click "Download .ts"
  • Replace original file
  • Test and verify types

3. Combine with Git:

# Format TypeScript code
# Then in terminal:
tsc --noEmit  # Verify types
npm test      # Run tests
git add .
git commit -m "Format TypeScript code"

Setting Up Team Standards

1. Document settings:

  • Preferred indent (e.g., 2 spaces)
  • Quote style (e.g., single quotes)
  • Semicolon policy (e.g., always)
  • Trailing comma style (e.g., ES5)

2. Add to project:

  • Include in README or CONTRIBUTING.md
  • Add .editorconfig file
  • Create .prettierrc for automation
  • Set up ESLint with TypeScript rules

3. Code review checklist:

  • Consistent indentation
  • Proper type annotations
  • Clean, readable formatting
  • No type errors (tsc --noEmit)

Quick Reference

Recommended Settings by Use Case

General TypeScript formatting:

  • Indent: 2 spaces
  • Quotes: Single
  • Semicolons: Add
  • Trailing comma: ES5
  • Arrow parens: Avoid

Enterprise/Microsoft style:

  • Indent: 4 spaces
  • Quotes: Double
  • Semicolons: Add
  • Trailing comma: ES5
  • Arrow parens: Avoid

Learning TypeScript:

  • Indent: 2 spaces (easy to read)
  • Quotes: Keep as-is (preserve examples)
  • Semicolons: Keep as-is
  • Focus on understanding types

Angular projects:

  • Indent: 2 spaces
  • Quotes: Single
  • Semicolons: Add
  • Trailing comma: All
  • Arrow parens: Always

Note: For production TypeScript projects, we recommend using Prettier with TypeScript support for consistent, automated code formatting. This tool is perfect for quick formatting, learning TypeScript, and privacy-focused use cases.

Frequently Asked Questions

Related Utility Tools

Share Your Feedback

Help us improve this tool by sharing your experience

We will only use this to follow up on your feedback