乐闻世界logo
搜索文章和话题

What is the Difference Between .ts and .tsx File Extensions in TypeScript?

2月7日 13:43

Introduction

TypeScript's extension design is rooted in its core objective of providing type safety and maintainability. .ts files are designed for pure TypeScript code, while .tsx integrates JavaScript XML (JSX) syntax, primarily used with frameworks like React. Confusing these extensions can lead to compilation errors or runtime issues, especially in large projects. According to the 2023 TypeScript Developer Report, approximately 68% of TypeScript beginners encounter build failures during project migration due to improper extension selection. This article explores the key differences from compilation mechanisms, syntax specifications, and practical examples to help developers avoid common pitfalls and optimize project practices.

Main Content

1. Definition and Compilation Mechanism of Extensions

  • .ts File: Pure TypeScript file containing only JavaScript syntax and type annotations, without JSX support. During compilation, the TypeScript compiler (tsc) transpiles it to standard JavaScript (.js) without processing JSX.

    • Key Features:
      • Used for non-UI component logic (e.g., utility functions, service layers).
      • Full type system support, but no JSX syntax.
      • Example:
        typescript
        // example.ts interface User { id: number; name: string; } function createUser(user: User): void { console.log(`User ${user.name} created`); }
  • .tsx File: File combining TypeScript and JSX syntax, recognized by the TypeScript parser as containing JSX. JSX is a syntax sugar for React, used for declarative UI descriptions.

    • Key Features:
      • Only used in React projects (requires react package configuration).
      • During compilation, TypeScript converts JSX to JavaScript objects (e.g., React.createElement), preserving type checking.
      • Example:
        tsx
        // example.tsx import React from 'react'; interface GreetingProps { name: string; } const Greeting: React.FC<GreetingProps> = ({ name }) => { return <div className="greeting">Hello, {name}!</div>; }; export default Greeting;

2. Core Difference Analysis

Feature.ts File.tsx File
Syntax SupportOnly JavaScript and TypeScript syntaxJavaScript, TypeScript, and JSX syntax
Compilation TargetStandard JavaScript (.js)Converted to React components (.js) via jsx compiler option
Applicable ScenariosServer-side logic, utility functions, non-UI codeReact components, UI rendering logic
Type CheckingStrict type checkingStrict type checking, with JSX elements needing React type constraints
  • Why .tsx Cannot Be Used Directly in Non-React Projects:
    • Using .tsx in a project without React dependencies causes TypeScript to report 'JSX' is not defined. This occurs because TypeScript requires the jsx: 'react' configuration (in tsconfig.json), otherwise it ignores JSX.
    • Practical Recommendations:
      • In React projects, must use .tsx extension; otherwise, JSX compilation fails.
      • In non-React projects, use .ts to avoid JSX-related errors.

3. Code Examples and Common Pitfalls

  • Trap 1: Confusing Extensions Causes Build Failures

    bash
    # Incorrect Example: Saving a React component as .ts tsc example.ts # Error: 'JSX' is not defined
    • Solution:
      1. Ensure tsconfig.json includes jsx: 'react'.
      2. Rename the file to .tsx.
  • Trap 2: Type System Differences In .tsx files, JSX elements must conform to React type constraints. For example:

    tsx
    // Correct: Using React.FC const Button: React.FC<{ text: string }> = ({ text }) => { return <button>{text}</button>; }; // Incorrect: Misusing JSX in .ts file (causes compilation error) // Cannot compile: TypeScript cannot recognize JSX in .ts
  • Best Practices:

    • Project Structure:
      • Place UI components in src/components/ using .tsx extension.
      • Place business logic in src/utils/ using .ts extension.
    • Configuration Recommendations:
      • Explicitly set in tsconfig.json:
        json
        { "compilerOptions": { "jsx": "react", "target": "ES2020" } }
      • Use tsdx or create-react-app for project initialization to automatically configure extensions.

4. Practical Case: Extension Selection in React Projects

In React applications, .tsx is mandatory:

  • Example Project Structure:
    bash
    src/ ├── components/ │ └── Button.tsx # Must use .tsx └── utils/ └── auth.ts # Use .ts
  • Why:
    • Saving Button as .ts causes TypeScript to reject JSX compilation, resulting in Error: JSX is not defined.
    • With the react package, TypeScript converts JSX to React.createElement, ensuring type safety.

Conclusion

The difference between .ts and .tsx extensions stems from TypeScript's support mechanism for JSX syntax. .ts is suitable for pure type-checking scenarios, while .tsx is designed specifically for React UI. Improper selection can result in build failures or maintenance challenges, but with proper configuration (e.g., tsconfig.json) and project structure organization, these issues can be easily avoided. It is recommended that developers always follow: UI components use .tsx, logic code uses .ts, and use TypeScript configuration tools (e.g., create-react-app) for new projects to handle extensions automatically. With TypeScript 5.0 introducing more flexible JSX options, future extension standards may evolve further, but current practices still prioritize clear differentiation as the core principle.

Appendix: TypeScript Official Documentation TypeScript Handbook | React JSX Guide

TypeScript vs JSX

Extended Thinking

In cross-framework projects (e.g., Next.js), .tsx files can be compatible with traditional React via jsx configuration, but note: Next.js defaults to jsx: 'preserve', which may affect performance. It is recommended to use tsdx or vite build tools in large projects for automatic optimization of extension handling.

标签:TypeScript